簡體   English   中英

向已在 Python 3 中打開的程序發送參數

[英]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 腳本

這不是進程間通信的工作方式。 您正在將命令行參數與標准輸入管道混合。

這將起作用:

接收.py:

import sys
import time
arguments = list(sys.argv)

while True:
    print(arguments)
    arguments.append(next(sys.stdin))

發送.py

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM