无法从subprocess调用Python脚本时传递参数

2024-04-18 23:10:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我找了这么多,但找不到一个新的。 我想从另一个python脚本(主脚本)调用一个python脚本(子脚本)。我不能把论点从父母传给孩子? 我希望控制台显示“subprocess launched:id1-id2”。 但我得到的是“子流程”启动:测试默认值". 子流程使用默认参数,而不是从父脚本接收参数。你知道吗

# parent
import subprocess
subprocess.call(['python', 'child.py', 'id1', 'id2'])

# script name: child.py
def child(id, id2):
    print ('subprocess launched: {}-{}'.format(str(id), id2))

if __name__ == '__main__':
    main(id='test', id2='default')

Tags: namepy脚本idchild参数main孩子
1条回答
网友
1楼 · 发布于 2024-04-18 23:10:33

传递给Python进程的参数存储在^{} [Python-doc]中。这是一个参数列表,其工作原理有点类似于^{} in ^{} [bash-man]。你知道吗

请注意,argv[0]不是第一个参数,而是您运行的Python脚本的名称,如文档所指定:

argv[0] is the script name (it is operating system dependent whether this is a full pathname or not).

其余参数是传递给脚本的参数。你知道吗

因此,您可以将child.py重写为:

# script name: child.py
from sys import argv

def child(id, id2):
    print ('subprocess launched: {}-{}'.format(str(id), id2))

if __name__ == '__main__':
    child(id=argv[1], id2=argv[2])

相关问题 更多 >