首页 > 解决方案 > 如何将值传递给 Popen.subprocess 内部的方法参数?

问题描述

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

标签: pythonpython-3.xsubprocesspopen

解决方案


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

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()

孩子.py:

import sys

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

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

推荐阅读