简体   繁体   English

使用参数执行子流程python脚本

[英]Execute subprocess python script with arguments

I have a python3 script that calls other python3 scripts using subprocess.Popen . 我有一个python3脚本,它使用subprocess.Popen调用其他python3脚本。
The first script creates a python object needed by the second script who will run a few times using the same object. 第一个脚本创建第二个脚本所需的python对象,第二个脚本将使用同一对象运行几次。

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. 但是我想将第一个脚本中创建的python对象传递给子进程。 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 . 根据文档, Args应该是字符串或字符串序列。 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. 但是,如果确实要传递对象,则可以将对象序列化为JSON,然后在第二个脚本中反序列化它以检索原始对象。 You may then proceed with the second script's operations 然后,您可以继续执行第二个脚本的操作

I have a python3 script that calls other python3 scripts using subprocess.Popen 我有一个使用subprocess.Popen调用其他python3脚本的python3脚本

ouch 哎哟

The first script creates a python object needed by the second script who will run a few times using the same object. 第一个脚本创建第二个脚本所需的python对象,第二个脚本将使用同一对象运行几次。

ouch^2 ouch ^ 2

However I want to pass to the subprocess the python object created in the first script. 但是我想将第一个脚本中创建的python对象传递给子进程。 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 :): 也演示了在python中做如此扭曲的事情是多么容易:):

python3: python3:

try1.py: 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: 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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