python - 遍历不终止的批处理脚本

标签 python windows batch-file subprocess

我正在尝试在 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/

相关文章:

Python 命名约定 : indicating if function alters arguments

c# - 如何拖放到 Windows Media Control

windows - 通过 CMD 的 FTP 文件以及创建日期

windows - 使用 {*.*} 从部分文件名创建文件夹

python - AUTOINCREMENT 列字段要求输入值

python - IPython 和 Jupyter 自动完成功能不起作用

python - Python中根据唯一键将列中的类别转换为编码为1或0的多列

python - Selenium Python 脚本在 Windows 和 Ubuntu 环境中有不同的行为

c++ - 算法库排序100万个0到1 float 的测时耗时

git - 将 git 包创建输出重定向到日志文件