主脚本在新的子进程和线程中启动第二个脚本,该脚本不断检查stdout中的数据。第二个脚本要求输入。我想让第一个脚本询问用户输入,然后将其传递给第二个脚本。我正在开发Windows并且无法让人工作。
test.py - 主脚本
import threading
import subprocess
def read_output(process):
print("starting to read")
for line in process.stdout:
print (line.rstrip())
def write_output(process,s):
process.stdin.write(s.encode('utf-8'))
process.stdin.flush()
process = subprocess.Popen('python test2.py', shell=False,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=None)
# Create new threads
thread1 = threading.Thread(read_output(process))
# Start new Threads
thread1.daemon=True
thread1.start()
s=input("test input:")
print("yep:"+s)
thread1.process.stdin.write(s.encode('utf-8'))
thread1.process.stdin.flush()
test2.py第二个脚本
print("Enter an input A,B,C:")
s=input("")
print("you selected:"+s)
答案 0 :(得分:1)
第一个错误:创建线程时出现错误的args。您正在传递在主进程中调用的函数的结果:线程尚未启动,您在主线程中读取输出,而不是在已启动的线程中读取。
修复如下:
thread1 = threading.Thread(target=read_output,args=(process,))
第二个错误(或者程序可能继续),你必须在写入字符串后关闭进程stdin:
process.stdin.close()
已修复test1.py
个文件:
import threading
import subprocess
def read_output(process):
print("starting to read")
for line in process.stdout:
print (line.rstrip())
process = subprocess.Popen('python test2.py', shell=False,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=None)
# Create new thread: pass target and argument
thread1 = threading.Thread(target=read_output,args=(process,))
# Start new Threads
thread1.daemon=True
thread1.start()
s=input("test input:")
print("yep:"+s)
process.stdin.write(s.encode('utf-8'))
process.stdin.write("\r\n".encode('utf-8')) # emulate "ENTER" in thread
process.stdin.close() # close standard input or thread doesn't terminate
thread1.join() # wait for thread to finish