[英]How to execute a file written in C from python while passing it string values and accepting/storing the string it returns as output.(Linux)
I have tried the subprocess module but providing the main function of C with string values but it doesn't seem to work for me.我已经尝试过 subprocess 模块,但是为 C 的主要功能提供了字符串值,但它似乎对我不起作用。 There are certain solutions available on the web but I'm having difficulty in understanding and implementing them.
网上有一些解决方案,但我很难理解和实施它们。 Any help will be appreciated.
任何帮助将不胜感激。
I want to execute a file written in C passing it arguments from my pyhthon code and after that C file is executed I want to capture what it returns in my python code.我想执行一个用 C 编写的文件,从我的 pyhthon 代码传递它的参数,在执行该 C 文件后,我想捕获它在我的 python 代码中返回的内容。
const char* main(int argc , char* argv[])
{
printf("Hello World from C \n");
printf("1st string passed is %s \n ",argv[1]);
printf("2nd string passed is %s \n ", argv[2]);
char b[] = "success";
return b;
}
This is the code in C from where I wish to return a string to the python code.这是我希望将字符串返回到 python 代码的 C 中的代码。
import subprocess
import os
def excuteC():
s = subprocess.call("./Cvishad hello you;", shell = True)
print("status is "+ str(s))
if __name__=="__main__":
excuteC()
This is the code in python where I am calling the C code.这是 python 中的代码,我在其中调用 C 代码。 It seems to work but I think it is returning a pointer/address but not the actual string "success" that I want.
它似乎有效,但我认为它返回的是一个指针/地址,而不是我想要的实际字符串“成功”。 The output I get is something like this -
我得到的输出是这样的 -
Hello World from C
1st string passed is hello
2nd string passed is you
status is 80
I'm trying out things for the first time in C, so kindly excuse the silly mistakes.我是第一次用 C 语言尝试一些东西,所以请原谅愚蠢的错误。
Your C program is returning a pointer to a string as the process return value, and it gets truncated to an unsigned byte (which you're seeing as eg 80).您的 C 程序正在返回一个指向字符串的指针作为进程返回值,它被截断为一个无符号字节(例如 80)。
You can transfer arbitrary data between processes by eg (and I'm sure I'm forgetting something)您可以通过例如在进程之间传输任意数据(我确定我忘记了一些东西)
subprocess.check_output()
in Python)subprocess.check_output()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.