简体   繁体   中英

How to execute a Python program from C in Linux

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.

To answer the problem as determined in the comments :

The OP was using execlp or the like, in the form:

execlp("python3", "name_of_script.py", (char*)0);

(or if they didn't know about the issue with NULL , they might have passed NULL instead of (char*)0 ).

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM