user2015487
user2015487

Reputation: 2185

Python how to pass a dictionary into a script using subprocess

I currently have a python script, scriptA.py, that accepts positional arguments and optional arguments. There are many positional arguments and many optional arguments, some of which are actionable (like flags), others take one argument or many (like a list).

Positional argument: Name
Optional argument: -Age
Optional argument: --favorite_sports 
Optional argument: -isAmerican   (if set, stores True, Default False)

Such that if you wanted to call scriptA.py, you could do so by:

python scriptA.py 'Bill' -Age 15 --favorite_sports basketball baseball -isAmerican

It is not important what scriptA.py does.

I have another script B, scriptB.py, that wants to call script A.py using subprocess. scriptB.py has the arguments that scriptA.py needs in a dictionary, but without knowledge of the dashes. Example:

d=dict() 
d['Name']=Bill 
d['Age']=15
d['favorite_sports']=['basketball', 'baseball']
d['isAmerican']=True

How can I run scriptB.py and inside the script call scriptA.py by using the dictionary d that is written in scriptB.py via subprocess?

Upvotes: 0

Views: 1827

Answers (1)

Yep_It's_Me
Yep_It's_Me

Reputation: 4801

Do you need to use subprocess? Why not just have a function in scriptA that accepts all the arguments as parameters? Something like this:

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)

Then from scriptB:

import scriptA

d=dict() 
d['Name']=Bill 
d['Age']=15
d['favorite_sports']=['basketball', 'baseball']
d['isAmerican']=True

scriptA.main(d)

If you need them to be processing simultaneously then maybe have a look at 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)

See this question for more on threads.

Upvotes: 1

Related Questions