sna*_*mer 6 python windows subprocess batch-file
我试图在python循环中执行几个批处理脚本.然而,所述bat-scripts包含cmd /K并因此不"终止"(因为没有更好的词).因此python调用第一个脚本并永远等待...
这是一个伪代码,可以让我了解我要做的事情:
import subprocess
params = [MYSCRIPT, os.curdir]
for level in range(10):
subprocess.call(params)
Run Code Online (Sandbox Code Playgroud)
我的问题是:"是否有一个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()
Run Code Online (Sandbox Code Playgroud)
exit这将向shell发送一个命令,该命令应在脚本终止时处理,导致其退出(有效地取消\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()
Run Code Online (Sandbox Code Playgroud)
这里的复杂之处在于读取输出,就好像您尝试读取超出可用范围的内容一样,该过程将被阻塞。
| 归档时间: |
|
| 查看次数: |
367 次 |
| 最近记录: |