在C ++中的system()函数调用的返回值,用于运行Python程序 [英] Return value of system() function call in C++, used to run a Python program

查看:634
本文介绍了在C ++中的system()函数调用的返回值,用于运行Python程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Linux上使用的代码,使 system()调用运行一个python程序。我对这个函数调用返回的值感兴趣,以了解python程序的执行过程。



到目前为止,我找到了3个结果:




  • 当python过程成功完成时,system()返回的值为0


  • p>当python进程在执行中被中断时(使用 kill -9 pid ),system()返回的值为9


  • 当python进程由于参数不正确而失败时,system()返回的值为512




这不符合我所阅读的有关 system() function。



此外,被调用的python程序的代码显示它退出 sys.exit(2)当遇到任何错误时, sys.exit(0)



关联这两个?我以错误的方式解释返回值?是否有一些Linux处理涉及到接受python程序的 sys.exit()函数的参数,并返回 system()根据它?

解决方案

调用的程序的退出代码可以用 WEXITSTATUS(status),根据手册页。另请参阅 等待 的手册页。

  int status = system(/ path / to / my / program); 
if(status< 0)
std :: cout<< Error:< strerror(errno)< '\\\
';
else
{
if(WIFEXITED(status))
std :: cout< 程序正常返回,退出代码< WEXITSTATUS(status)<< '\\\
';
else
std :: cout<< 程序退出异常
}


I am working on Linux with code that makes a system() call to run a python program. I am interested in the value returned by this function call to understand how the python program execution went.

So far, I have found 3 results:

  • When the python process completes successfully, value returned by system() is 0

  • When the python process is killed mid-execution (using kill -9 pid), value returned by system() is 9

  • When the python process fails on its own due to incorrect parameters, value returned by system() is 512

This does not fit with what I've read about system() function.

Furthermore, the code for the python program being invoked shows that it exits with sys.exit(2) when any error is encountered, and sys.exit(0) when execution completes successfully.

Could anyone relate these two? Am I interpreting the return value in a wrong manner? Is there some Linux processing involved that takes the argument of the sys.exit() function of the python program and returns value of system() based on it?

解决方案

The exit code of the program you call can be fetched with WEXITSTATUS(status) as per the manual page. Also see the manual page for wait.

int status = system("/path/to/my/program");
if (status < 0)
    std::cout << "Error: " << strerror(errno) << '\n';
else
{
    if (WIFEXITED(status))
        std::cout << "Program returned normally, exit code " << WEXITSTATUS(status) << '\n';
    else
        std::cout << "Program exited abnormaly\n";
}

这篇关于在C ++中的system()函数调用的返回值,用于运行Python程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆