从 c++ 中运行 python 脚本,找不到模块

Run python script from within c++, modules not found

本文关键字:找不到 模块 脚本 python c++ 运行      更新时间:2023-10-16

OSX 10.12

我正在尝试使用execlp()调用(在分叉线程中(从 c 中启动我制作的 python 脚本。我可以通过命令行很好地运行脚本,但是从应用程序中我收到一条错误消息,说它找不到模块。例如,我什至尝试在全球范围内安装模块,例如sudo -H pip install requests但仍然找不到模块。我的 python 脚本像往常一样导入模块:

import requests
from bs4 import BeautifulSoup
html = requests.get('https://www.douyu.com/directory/all').text
soup = BeautifulSoup(html, 'html.parser')
urls = soup.select('.play-list-link')
output = '';
output += '[' #open json array
for i, url in enumerate(urls):
channelName = str(i);
channelUrl = 'http://douyu.com' + url.get('href')
output += '{'
output += '"channelName":' + '"' + channelName.encode('utf-8') + '",'
output += '"channelUrl":' + '"' + channelUrl.encode('utf-8') + '"'
output += '},'
output = output[:-1] # remove last comma
output += ']' # close json array
print output

我从 c++ 应用程序中的执行如下所示(execlp()行实际上是我在这里向您展示的全部内容(:

int pid = fork();
switch(pid){
case -1:{
perror("fork");
_exit(EXIT_FAILURE);
break;
}
case 0:{ // child process
// create output file
int out = creat(jsonFilePath.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (out == -1){ //if failed to create output file, terminate child process
perror("creat");
_exit(EXIT_FAILURE);
} else {
dup2(out,STDOUT_FILENO); // redirect stdout to output file
execlp("python","python",pythonScript.c_str(), NULL); // exec the command
close(out); // close output file
_exit(0); //exit child process
}
break;
}
default:{
// wait for child process
int status = 0;
waitpid(-1, &status, WNOHANG);
printf("child status:%dn",status);
break;
}
}
forkOnce_getJson = true;

这些模块如何被其他应用程序发现,如果不是全局的,至少在虚拟环境之外?提前感谢!!

正如@abarnert上面的评论中所指出的,我使用了错误的路径。我应该从我的 cpp 程序执行的正确 python 版本是usr/local/bin/python.