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

标签 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传值?

最佳答案

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

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)

关于python - 如何将值传递给 Popen.subprocess 内的方法参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52478339/

相关文章:

python - 输出子进程调用的命令行?

python - 使用子进程模块从 python 启动 jython 程序?

python - Selenium (with python) 如何修改元素的 css 样式

django - 如何更改 'localhost' url django

python-3.x - Jupyter笔记本电脑随机停止使用所有CPU内核

python - web.py 应用程序上的 Pytests 未覆盖方法代码

python - 如何在标记 Keras 时忽略字符

python - 如何查看程序的源代码(python)

Flutter 移动应用程序中的 Python 和 Dart 集成

python - 删除 Unix/bash 中与列条件匹配的行