[英]Run python script from within c++, modules not found
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:%d\n",status);
break;
}
}
forkOnce_getJson = true;
如果无法在全局范围内(至少在virtualenv之外)被其他应用程序发现,这些模块又如何? 提前致谢!!
正如@abarnert在上述评论中指出的那样,我使用了错误的PATH。 我应该从cpp程序执行的正确python版本位于usr/local/bin/python
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.