简体   繁体   中英

Execute subprocess python script with arguments

I have a python3 script that calls other python3 scripts using subprocess.Popen .
The first script creates a python object needed by the second script who will run a few times using the same object.

Right now it looks like this:

for x in range(0,10):
    pid2 = subprocess.Popen([sys.executable, "try2.py"])

However I want to pass to the subprocess the python object created in the first script. Is this possible? Or can I only pass string arguments?

Thanks.

Args is supposed to be either a string or a sequence of strings as per the documentation . But if you do want to pass an object, you could perhaps serialize the object into JSON, then deserialize it back in your second script to retrieve the original object. You may then proceed with the second script's operations

I have a python3 script that calls other python3 scripts using subprocess.Popen

ouch

The first script creates a python object needed by the second script who will run a few times using the same object.

ouch^2

However I want to pass to the subprocess the python object created in the first script. Is this possible? Or can I only pass string arguments?

You can only pass string arguments but you can serialize the object before passing it.

You mind sharing more about the problem you are trying to solve so we can come up with a well structured maintainable solution?

Just too demonstrate how easy it is in python to do even so twisted things :):

python3:

try1.py:

import subprocess
import sys
import pickle
import base64


class X:
    def __init__(self):
        self.a = 2

a = X()
a.a = "foobar"

subprocess.call([sys.executable, "try2.py", base64.encodestring(pickle.dumps(a))])

try2.py:

import sys
import pickle
import base64


class X:
    def __init__(self):
        self.a = 2

x = pickle.loads(base64.decodestring(bytes(sys.argv[1], "ascii")))
print(x.a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM