使用子进程将参数传递给 python 函数

Pass arguments to python functions using subprocess

如果我在这样的文件中有一个函数:

def foo():
    print 'foo'

foo()

我可以从另一个文件调用这个文件:

import subprocess
subprocess.call(['python', 'function.py'])

但如果函数需要参数则可以:

def foo(foo_var):
    print foo_var

我还能使用子进程调用函数吗?

Can I still call the function using subprocess?

是的。

首先,您需要将参数传递给函数:

from sys import argv

def foo(args):
    print args
    >> ['arg1', 'arg2']  # (based on the example below)

foo(argv[1:])

然后在你的调用代码中:

import subprocess
subprocess.call(['python', 'function.py', 'arg1', 'arg2'])

而不是使用 subprocess,只需修改 function.py 即可使其与导入很好地配合使用:

def foo():
    print 'foo'

if __name__ == '__main__':
    foo()

然后你可以从 function 模块导入 foo:

from function import foo

if __name__ == '__main__':
    foo(1)