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

时间:2018-05-06 00:17:54

标签: python c++ pip exec

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之外,其他应用程序如何能够发现这些模块?在此先感谢!!

1 个答案:

答案 0 :(得分:0)

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