python 运行脚本附带参数,带参数运行python脚本

I want to call a Python script from C, passing some arguments that are needed in the script.

The script I want to use is mrsync, or multicast remote sync. I got this working from command line, by calling:

python mrsync.py -m /tmp/targets.list -s /tmp/sourcedata -t /tmp/targetdata

-m is the list containing the target ip-addresses.

-s is the directory that contains the files to be synced.

-t is the directory on the target machines where the files will be put.

So far I managed to run a Python script without parameters, by using the following C program:

Py_Initialize();

FILE* file = fopen("/tmp/myfile.py", "r");

PyRun_SimpleFile(file, "/tmp/myfile.py");

Py_Finalize();

This works fine. However, I can't find how I can pass these argument to the PyRun_SimpleFile(..) method.

解决方案

Seems like you're looking for an answer using the python development APIs from Python.h. Here's an example for you that should work:

#My python script called mypy.py

import sys

if len(sys.argv) != 2:

sys.exit("Not enough args")

ca_one = str(sys.argv[1])

ca_two = str(sys.argv[2])

print "My command line args are " + ca_one + " and " + ca_two

And then the C code to pass these args:

//My code file

#include

#include

void main()

{

FILE* file;

int argc;

char * argv[3];

argc = 3;

argv[0] = "mypy.py";

argv[1] = "-m";

argv[2] = "/tmp/targets.list";

Py_SetProgramName(argv[0]);

Py_Initialize();

PySys_SetArgv(argc, argv);

file = fopen("mypy.py","r");

PyRun_SimpleFile(file, "mypy.py");

Py_Finalize();

return;

}

If you can pass the arguments into your C function this task becomes even easier:

void main(int argc, char *argv[])

{

FILE* file;

Py_SetProgramName(argv[0]);

Py_Initialize();

PySys_SetArgv(argc, argv);

file = fopen("mypy.py","r");

PyRun_SimpleFile(file, "mypy.py");

Py_Finalize();

return;

}

You can just pass those straight through. Now my solutions only used 2 command line args for the sake of time, but you can use the same concept for all 6 that you need to pass... and of course there's cleaner ways to capture the args on the python side too, but that's just the basic idea.

Hope it helps!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值