C 相当于 Python 的 exec() 函数



我在互联网上以各种方式搜索,但没有一个结果能回答我的问题,也许我会在这里找到解决方案。

在python中,我可以这样做:

imp = "import os"
exec(imp)
os.system("ping x.x.x.x")

在C语言中,这个精确的函数调用的等价物是什么?

在C语言中,这个精确的函数调用的等价物是什么?

Python中的exec()将尝试以Python的形式执行任何字符串。C或C++中的system()(或任何其他语言中的等效system()调用,例如Python中的os.system()(将尝试将任何字符串作为系统调用来执行,系统调用是您的shell语言,可以是Bash、Python、Perl、另一个C可执行文件或任何其他可执行文件

所以,没有确切的等价物。但是,最接近的可能是system()调用,它可以将任何字符串作为命令行命令进行调用,就像您在终端键入它一样

然而,Csystem()调用实际上与Pythonos.system()调用完全等效。通常,只有脚本编程语言具有exec()调用,而所有或大多数编程语言都具有system()调用。C(我想,一般来说,因为可能有C解释器(是一种编译的语言,而不是脚本语言。

更进一步,如果您需要从您调用的命令中读取stdout或stderr输出,则需要使用管道作为进程间通信(IPC(机制将其管道返回到您的进程(因为它是在新进程中派生的(。您可以通过调用popen()打开IPC管道。你可以用它来代替system()呼叫。请参阅此处的示例:如何从C运行外部程序并解析其输出?

下面是我在Linux Ubuntu上测试的system()调用示例。你会喜欢的!光看它就让我笑。但是,它很有见地,也很有启发性,如果你仔细想想,它会带来很多非常酷的可能性。

system_call_python.c(有关此代码的最新版本,请参阅我的eRCaGuy_hello_world repo中的system_call_prython.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代码自动生成(请在我的eRCaGuy_hello_world repo中查看(:

imp = "import os"
exec(imp)
os.system("ping 127.0.0.1")

所以你有了它:让C用Bash或Python构建一些程序,然后让C调用它。或者,你可以让C用C构建一个程序,让它编译,然后调用它——一个编写程序的程序。

最新更新