我正在尝试在 python 循环中执行多个批处理脚本。然而,上述 bat 脚本包含 cmd/K
,因此不会“终止”(因为缺少更好的词)。因此 python 调用第一个脚本并永远等待...
这是一个伪代码,它给出了我正在尝试做的事情的想法:
import subprocess
params = [MYSCRIPT, os.curdir]
for level in range(10):
subprocess.call(params)
我的问题是:“是否有 pythonic 解决方案来恢复控制台命令并恢复循环?”
编辑:我现在知道可以启动子进程并继续,而无需等待它们返回,使用
Popen(params,shell=False,stdin=None,stdout=None,stderr=None,close_fds=True)
然而,这将几乎同时启动我的整个循环。有没有办法等待子进程执行其任务并在它点击 cmd/K
并变为空闲时返回。
最佳答案
没有内置方法,但您可以实现。
示例是 bash,因为我无法访问 Windows 机器,但 cmd\K
应该类似
它可能很简单:
import subprocess
# start the process in the background
process = subprocess.Popen(
['bash', '-i'],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE
)
# will throw IO error if process terminates by this time for some reason
process.stdin.write("exit\n")
process.wait()
这将向 shell 发送一个 exit
命令,应该在脚本终止导致它退出时处理该命令(有效地取消 \K
)
如果您需要检查某些输出的解决方案,这里有一个更详尽的答案:
import subprocess
# start the process in the background
process = subprocess.Popen(
['bash', '-i'],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE
)
# Wait for the process to terminate
process.poll()
while process.returncode is None:
# read the output from the process
# note that can't use readlines() here as it would block waiting for the process
lines = [ x for x in process.stdout.read(5).split("\n") if x]
if lines:
# if you want the output to show, you'll have to print it yourself
print(lines )
# check for some condition in the output
if any((":" in x for x in lines)):
# terminate the process
process.kill()
# alternatively could send it some input to have it terminate
# process.stdin.write("exit\n")
# Check for new return code
process.poll()
这里的复杂之处在于读取输出,如果您尝试读取超出可用范围的内容,进程就会阻塞。
关于python - 遍历不终止的批处理脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41020607/