Angel
Angel

Reputation: 31

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.

Upvotes: 0

Views: 1245

Answers (2)

luv
luv

Reputation: 432

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)

Upvotes: 0

Anoop R Desai
Anoop R Desai

Reputation: 720

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

Upvotes: 1

Related Questions