[英]Sending arguments to a program that is already open in Python 3
我想要做的在这里更好地解释: 发送到 python3 中程序的标准输入
我试图在程序打开时向程序发送参数,例如:
接收文件
import sys
import time
while True:
print(sys.argv)
time.sleep(1)
发送.py
import subprocess
program = Popen(['python.exe', 'rec.py', 'testArg'])
a = input('input: ')
a.communicate(b)
我希望能够运行 send.py 并输入我的输入。 假设我的输入是“cat”,当我运行 send.py 时,我希望输出看起来像这样
['rec.py', 'testArg']
['rec.py', 'testArg']
['rec.py', 'testArg']
cat <------- My input
['rec.py', 'testArg', 'cat']
['rec.py', 'testArg', 'cat']
['rec.py', 'testArg', 'cat']
['rec.py', 'testArg', 'cat']
等..
我是否错误地使用了 subprocess.Popen.communicate() 还是其他什么?
请帮忙!
-谢谢
程序启动后不能更改命令行参数,即sys.argv
只能从进程本身的内部(通常)更改。
Popen.communicate(input=data)
可以通过其标准输入将data
发送到子进程(如果您将stdin=PIPE
传递给Popen()
)。 .communicate()
在返回之前等待进程退出,因此它可用于一次发送所有输入。
要增量发送输入,请直接使用process.stdin
:
#!/usr/bin/env python3
import sys
import time
from subprocess import Popen, PIPE
with Popen([sys.executable, 'child.py'],
stdin=PIPE, # redirect process' stdin
bufsize=1, # line-buffered
universal_newlines=True # text mode
) as process:
for i in range(10):
time.sleep(.5)
print(i, file=process.stdin, flush=True)
其中child.py
:
#!/usr/bin/env python3
import sys
for line in sys.stdin: # read from the standard input line-by-line
i = int(line)
print(i * i) # square
更好的选择是导入模块并使用其功能。 请参阅使用子进程在 python 脚本中使用输入调用 python 脚本
这不是进程间通信的工作方式。 您正在将命令行参数与标准输入管道混合。
这将起作用:
import sys
import time
arguments = list(sys.argv)
while True:
print(arguments)
arguments.append(next(sys.stdin))
import subprocess
program = subprocess.Popen(['python.exe', 'rec.py', 'testArg'], stdin=subprocess.PIPE)
a = input('input: ')
program.stdin.write(a + '\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.