我需要从 C 调用 python 脚本并能够从中捕获返回值。值是什么并不特别重要,它们也可能是一个枚举,但我从测试用例中得到的值让我感到困惑,我想深入了解我所看到的。
所以,这是 C:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int out = 0;
out = system("python /1.py");
printf("script 1 returned %d\n", out);
return 0;
}
这里是 /1.py
:
import sys
sys.exit(1)
这些程序的输出是这样的:
script 1 returned 256
一些其他值:
2 -> 512
800 -> 8192
8073784 -> 14336
假设它是……以小字节序而不是大字节序读取,还是什么?我如何编写一个 c 函数(或欺骗 python)来正确返回和解释数字?
最佳答案
来自 Linux documentation在系统上():
... return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status) ...
通过wait
上的链接,我们得到以下信息:
WEXITSTATUS(status): returns the exit status of the child. ... This macro should only be employed if WIFEXITED returned true.
这相当于你不能直接使用system()
的返回值,而必须使用宏来操作它们。而且,由于这符合 C 标准而不仅仅是 Linux 实现,您将需要对您正在使用的任何操作环境使用相同的过程。
关于python - c system() 从 python 脚本返回 - 令人困惑!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4111279/