在 C 语言中这个精确的函数调用的等价物是什么?
exec() 在 Python 中将尝试将任何字符串作为 Python 执行。 C 或 C++ 中的 system()(或任何其他语言中的等效 system() 调用,就此而言,例如 Python 中的 os.system())将尝试将任何字符串作为系统调用执行,这是您的 shell 语言,可以是Bash、Python、Perl、另一个 C 可执行文件或其他任何与此相关的东西。
因此,没有完全等价的。但是,最接近的可能是system() 调用,它可以调用任何字符串作为命令行命令,就像您在终端上键入一样。
然而,C system() 调用实际上与 Python os.system() 调用完全等效。通常,只有 脚本化 编程语言有 exec() 调用,而所有或大多数编程语言都有 system() 调用。 C(一般来说,我想,因为那里可能有 C 解释器)是一种编译语言,而不是一种脚本语言。
更进一步,如果您需要从您调用的命令中读回 stdout 或 stderr 输出,您需要使用管道将其返回到您的进程(因为它是在新进程中生成的) pipe 作为进程间通信 (IPC) 机制。您可以通过调用popen() 打开 IPC 管道。您可以使用它来代替 system() 调用。示例见此处:How can I run an external program from C and parse its output?
这是我在 Linux Ubuntu 上测试的 system() 调用示例。你会喜欢这个的!光是看着就让我发笑。但是,它仍然很有洞察力和启发性,如果你仔细想想,它会开启大量非常酷的可能性。
system_call_python.c:
#include <stdlib.h> // For `system()` calls
#include <stdio.h> // For `printf()
#define PYTHON_CODE \
"imp = \"import os\"\n" \
"exec(imp)\n" \
"os.system(\"ping 127.0.0.1\")\n"
int main()
{
system("echo '" PYTHON_CODE "' > myfile.py");
system("python3 myfile.py");
return 0;
}
构建并运行 cmd + 输出:
eRCaGuy_hello_world/c$ mkdir -p bin && gcc -O3 -std=c11 -save-temps=obj system_call_python.c -o bin/system_call_python && bin/system_call_python
system_call_python.c: In function ‘main’:
system_call_python.c:41:5: warning: ignoring return value of ‘system’, declared with attribute warn_unused_result [-Wunused-result]
system("echo '" PYTHON_CODE "' > myfile.py");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
system_call_python.c:42:5: warning: ignoring return value of ‘system’, declared with attribute warn_unused_result [-Wunused-result]
system("python3 myfile.py");
^~~~~~~~~~~~~~~~~~~~~~~~~~~
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.024 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.084 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.082 ms
64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.086 ms
这是 myfile.py 的样子,上面的 C 代码自动生成:
imp = "import os"
exec(imp)
os.system("ping 127.0.0.1")
这样就完成了:让 C 在 Bash 或 Python 中构建一些程序,然后让 C 调用它。或者,您可以让 C 在 C 中构建一个程序并让它编译然后调用它——一个编写程序的程序。