【问题标题】:How to pass value to method argument which is inside Popen.subprocess?如何将值传递给 Popen.subprocess 内部的方法参数?
【发布时间】:2019-02-27 21:45:37
【问题描述】:

这是我的主要 python 脚本:

import time
import subprocess
def main():
   while(True):
       a=input("Please enter parameter to pass to subprocess:")
       subprocess.Popen(args="python child.py")
       print(f"{a} was started")
       time.sleep(5)
if __name__ == '__main__':
    main()

这是名为 child.py 的 python 子脚本:

def main(a):
    while(True):
        print(a)

if __name__ == '__main__':
    main(a)

如何将值传递给子子进程中的参数a?

【问题讨论】:

  • 如果你想连续传递一个值给子进程:你可以像@Poolka那样使用管道或者使用socket来读写数据。

标签: python python-3.x subprocess popen


【解决方案1】:

你需要使用命令行参数,像这样;

import time
import subprocess

def main():
   while(True):
       a=input("Please enter parameter to pass to subprocess:")
       subprocess.Popen(["python", "child.py", a])
       print(f"{a} was started")
       time.sleep(5)

if __name__ == '__main__':
    main()

child.py:

import sys

def main(a):
    while(True):
        print(a)

if __name__ == '__main__':
    a = sys.argv[1]
    main(a)

【讨论】:

    【解决方案2】:

    您可以使用subprocess.PIPE 在您的主进程和衍生的子进程之间传递数据。

    主脚本:

    import subprocess
    
    
    def main():
        for idx in range(3):
            a = input(
                'Please enter parameter to pass to subprocess ({}/{}): '
                .format(idx + 1, 3))
            print('Child in progress...')
            pipe = subprocess.Popen(
                args='python child.py',
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE)
            pipe.stdin.write(str(a).encode('UTF-8'))
            pipe.stdin.close()
            print('Child output is:')
            print(pipe.stdout.read().decode('UTF-8'))
    
    
    if __name__ == '__main__':
        main()
    

    子脚本:

    import sys
    import time
    
    
    def main(a):
        for dummy in range(3):
            time.sleep(.1)
            print(a)
    
    
    if __name__ == '__main__':
        a = sys.stdin.read()
        main(a)
    

    输出:

    >>> python main.py
    Please enter parameter to pass to subprocess (1/3): qwe
    Child in progress...
    Child output is:
    qwe
    qwe
    qwe
    
    Please enter parameter to pass to subprocess (2/3): qweqwe
    Child in progress...
    Child output is:
    qweqwe
    qweqwe
    qweqwe
    
    Please enter parameter to pass to subprocess (3/3): 123
    Child in progress...
    Child output is:
    123
    123
    123
    

    【讨论】:

    • 如果您想不断地向孩子传递一些价值,这是正确的答案。
    • 嗨@Poolka 非常感谢你 - 一切正常,你能告诉我你在哪里找到有关命令 pipe.stdin.write(str(a).encode('UTF-8') 的信息吗) ?我阅读了docs.python.org/3/library/subprocess.html,但没有找到有关该命令的信息。实际上,在我看来,我没有从标准库中学习编写方式,因为我经常无法从中获得必要的信息。
    • @ArtiomKozyrev 我是从 Mark Summerfield 的 Programming in Python 3: Complete Introduction 那里学到的。这本书是英文的,有点过时(它是关于 Python 3.1),但它是一个真正的 complete 介绍(不是很深,但很广泛)。我想(虽然不确定)这本书还有更多新鲜的替代品。
    • @ArtiomKozyrev The Python 3 Standard Library by Example by Doug Hellmann 似乎对 Python 3 标准库的潜力有相当广泛的覆盖。只是基于目录的意见。不确定它是否免费提供。
    【解决方案3】:

    将参数传递给子进程的最简单方法是使用command line parameters

    第一步是重写child.py,使其接受命令行参数。这个问题中有关于解析命令行参数的详细信息:How to read/process command line arguments? 不过对于这个简单的例子,我们将简单地通过sys.argv 访问命令行参数。

    import sys
    
    def main(a):
        while(True):
            print(a)
    
    if __name__ == '__main__':
        # the first element in the sys.argv list is the name of our program ("child.py"), so
        # the argument the parent process sends to the child process will be the 2nd element
        a = sys.argv[1]
        main(a)
    

    现在child.py 可以以python child.py foobar 之类的参数开头,文本“foobar”将用作a 变量的值。

    除此之外,剩下的就是重写parent.py 并使其将参数传递给child.py。使用subprocess.Popen 传递参数的推荐方法是作为字符串列表,因此我们将这样做:

    import time
    import subprocess
    
    def main():
       while(True):
           a = input("Please enter parameter to pass to subprocess:")
           subprocess.Popen(["python", "child.py", a])  # pass a as an argument
           print(f"{a} was started")
           time.sleep(5)
    
    if __name__ == '__main__':
        main()
    

    【讨论】:

      猜你喜欢
      • 2016-05-12
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      • 2014-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多