如何在Linux中从C执行Python程序 [英] How to execute a Python program from C in Linux
问题描述
我正在使用Raspberry Pi,并且我的C程序完成功能运行后,我需要能够执行python程序.我一直在尝试使用fork和exec,但是,当我使用python3作为exec函数的第一个参数时,我得到的只是控制台中的python命令提示符.
I'm using a Raspberry Pi and I need to be able to execute a python program once my C program finishes running a function. I've been trying to use fork and exec, however, when I use "python3" as the first parameter for the exec function, all I get is the python command prompt in the console.
推荐答案
要回答问题 OP正在使用 execlp
或类似形式,
The OP was using execlp
or the like, in the form:
execlp("python3", "name_of_script.py", (char*)0);
(或者,如果他们不知道 NULL
的问题,他们可能已经传递了 NULL
而不是(char *)0
).
(or if they didn't know about the issue with NULL
, they might have passed NULL
instead of (char*)0
).
问题是, execlp
通常需要传递第一个参数两次;第二次是将其设置为 argv [0]
的值,而几乎总是在 argv [1]
和更高版本中检查用户提供的参数( argv [0]
很少使用,当使用时,主要用于用法/调试输出).当 python3
看到其自己的 argv
时,它会看到它是用 name_of_script.py
的名称"调用的,但没有看到它是一个真正的参数",因此它就像没有参数启动一样,从而产生了交互式解释器.
Problem is, execlp
usually needs the first argument to be passed twice; the second time it's the value to be set as argv[0]
, while user-supplied arguments are almost always checked for in argv[1]
and higher (the value in argv[0]
is rarely used, and when it is, it's mostly for usage/debug output). When python3
sees its own argv
, it sees that it's been invoked with the "name" of name_of_script.py
, but it doesn't see it as a real "argument", so it acts as if it were launched with no arguments, which leads to the interactive interpreter.
解决方法是两次传递程序名称,一次找到程序,一次在 argv
中进行设置,因此参数被 python3
识别为脚本调用:
The fix is to pass the program name twice, once to find the program, once to set it in argv
, so the argument is recognized by python3
as a script to invoke:
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
这篇关于如何在Linux中从C执行Python程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!