Python 如何通过subprocess将字典传递给脚本
我现在有一个Python脚本,叫做scriptA.py,它可以接受位置参数和可选参数。位置参数和可选参数有很多,有些是可以直接使用的(像标志),有些需要一个或多个参数(像列表)。
Positional argument: Name
Optional argument: -Age
Optional argument: --favorite_sports
Optional argument: -isAmerican (if set, stores True, Default False)
也就是说,如果你想调用scriptA.py,你可以这样做:
python scriptA.py 'Bill' -Age 15 --favorite_sports basketball baseball -isAmerican
scriptA.py具体做什么并不重要。
我还有另一个脚本B,叫做scriptB.py,它想通过子进程来调用scriptA.py。scriptB.py里有一个字典,里面存着scriptA.py需要的参数,但没有带上那些破折号。举个例子:
d=dict()
d['Name']=Bill
d['Age']=15
d['favorite_sports']=['basketball', 'baseball']
d['isAmerican']=True
我该如何运行scriptB.py,并在这个脚本里通过字典d来调用scriptA.py,使用子进程呢?
1 个回答
1
你真的需要用到子进程吗?为什么不直接在scriptA里写一个函数,让它接受所有参数呢?可以这样做:
def main(args={}):
pass
if __name__ == '__main__':
d=dict()
d['Name']= # get name
d['Age']= # get age
d['favorite_sports']=[#fav_sports]
d['isAmerican']= #true or false
main(d)
然后在scriptB中:
import scriptA
d=dict()
d['Name']=Bill
d['Age']=15
d['favorite_sports']=['basketball', 'baseball']
d['isAmerican']=True
scriptA.main(d)
如果你需要它们同时处理,那可以看看threading
这个模块:
import scriptA
from threading import Thread
d=dict()
d['Name']=Bill
d['Age']=15
d['favorite_sports']=['basketball', 'baseball']
d['isAmerican']=True
thread = Thread(target = scriptA.main, args = d)
想了解更多关于线程的内容,可以查看这个问题。