我使用的是 Raspberry Pi,当我的 C 程序完成运行函数后,我需要能够执行 python 程序。我一直在尝试使用 fork 和 exec,但是,当我使用“python3”作为 exec 函数的第一个参数时,我得到的只是控制台中的 python 命令提示符。
最佳答案
回答问题as determined in the comments :
OP 使用 execlp
或类似的形式:
execlp("python3", "name_of_script.py", (char*)0);
(或者如果他们不知道 the issue with NULL
,他们可能会传递 NULL
而不是 (char*)0
)。
问题是,execlp
usually needs the first argument to be passed twice ;第二次它的值被设置为 argv[0]
,而用户提供的参数几乎总是在 argv[1]
及更高版本中检查(中的值) argv[0]
很少使用,即使使用,也主要用于使用/调试输出)。当python3
看到它自己的argv
时,它看到它是用name_of_script.py
的“名称”调用的,但它没有看到它作为一个真正的“参数”,所以它的行为就好像它是在没有参数的情况下启动的,这导致了交互式解释器。
修复方法是传递程序名称两次,一次用于查找程序,一次将其设置在 argv
中,因此参数被 python3
识别为脚本调用:
execlp("python3", "python3", "name_of_script.py", (char*)0);
// ^ program to find
// ^ name to set in argv[0]
// ^ script name to put in argv[1] so script is run
关于python - 如何在 Linux 中用 C 语言执行 Python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52282245/