如何将值传递给Popen.subprocess内部的方法参数?

时间:2018-09-24 11:26:50

标签: python python-3.x subprocess popen

这是我的主要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?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

将参数传递给子进程的最简单方法是使用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()

答案 2 :(得分: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)