看起来像是子流程.波彭没有松开锁



我正试图通过python执行一个批处理脚本,看起来像是子流程。Popen正在执行命令,它被卡在终端上,尽管复制完成,但没有打印任何输出。你能帮忙吗。

ps_copy_command = "call copyfiles.cmd"
process=subprocess.Popen(["cmd", "/C", ps_copy_command, password], stdout=subprocess.PIPE, stderr=subprocess.PIPE);
process.wait()
print("tCopy completed ")
output = process.stdout.read()
print (output)

如果代码是在output = process.stdout.read()中学习的,那么不久前我也发生了类似的事情。问题是process.stdout.read((在stdout中有内容之前不会返回内容。示例:

想象一下,您的批处理脚本正在执行一些需要10秒的任务,然后打印"完成!">

python要等到"完成!"由脚本返回。

他们解决这个问题的方法是添加线程。一个线程正在读取stdout,另一个正在等待n秒,然后我加入等待线程,如果stdout线程中有内容,我会将其打印为

import time
import threading
def wait_thread():
seconds = 0
while seconds < 2:
time.sleep(1)
seconds += 1
return True
def stdout_thread():
global output
output = process.stdout.read()

output=None
t1 = threading.Thread(target=wait_thread)
t2 = threading.Thread(target=stdout_thread)
t1.start()
t2.start()
t1.join()     # wait until waiting_thread is end  
if output:
print(output)
else:
print("No output")

我正在使用subprocess.run来解决这个问题。

process=subprocess.run(["cmd", "/C", ps_copy_command, password], stdout=subprocess.PIPE);
print(process.returncode)
print(process.stdout)

相关内容

最新更新