我正在尝试使用Python subprocess.Popen 来运行批处理文件,该文件执行 xfoil.exe 并为其提供一些参数 . 然后等待直到xfoil.exe退出 .

我已经使用以下代码作为批处理运行程序,它等待进程以超时退出 . 如果超时,该过程将被终止 .

def Bat_Runner(args, **kwargs):
    """
    Batch runner
    :param args:
    :return:
    """
    si = STARTUPINFO()
    si.dwFlags |= STARTF_USESHOWWINDOW
    process = Popen(args, stdin=PIPE, stdout=DEVNULL, bufsize=1, universal_newlines=True)
    try:
        process.wait(kwargs['timeout'])
    except KeyError:
        process.wait()
    except TimeoutExpired:
        process.kill()
        raise TimeoutError

但是,有时 xfoil.exe 失败并挂起,在这种情况下批处理文件也会挂起,主程序卡在 process.wait(kwargs['timeout]) . 即使达到时间限制,批处理也不会被终止 . 在这种情况下,如果我通过双击"XXX.bat"手动运行批处理文件,控制台窗口也会挂起 .

这是什么原因?我对此有点疑惑,因为 Bat_Runner 函数已经过测试,在某些情况下可以很好地杀死这个过程,但不是这种情况 .

此外,如果 kill() 正在杀死批处理进程,有没有办法杀死它调用的 xfoil.exe 进程?

更新行======================= ========

PS:

1此代码将调用此Bat_Runner函数:

def _solve_by_Xfoil(self, alpha_set, Mach_number, Raynolds_number, parameter, is_viscus=True, **kwargs):
    ...many unrelated codes...
    try:
        if kwargs.get('timeout'):
            Bat_Runner(batch_file__bat, timout=kwargs['timeout'])
        else:
            Bat_Runner(batch_file__bat, timeout=5)
    except TimeoutError:
        print(''.join((Print_Colors.FAIL, 'Warning!\n', Print_Colors.ENDC,
               'Current Airfoil {} Cannot get an Output: {}!')).format(self._name, parameter))

代码相对较大,所以为了简化,我只是展示了什么是重要的 . 理论上它会打印出一个失败的信息 . _solve_by_Xfoil将通过以下方式调用:

cl_str_list = self._solve_by_Xfoil(alpha_range, Mach_number, Raynolds_number, 'CL', is_viscus=is_viscus,timeout=10, **kwargs)

batch_file__bat(与XXX.bat相同)是一个包含以下内容的文件:

xfoil.exe <xfoil_batch_pid_11028.dat

2对于参考, xfoil.exe 是这个opensource program,我'm using its excutable exe file in this case, it will show a console window, just type some instructions to make it run, so I' m使用批处理文件来运行它 .

3当 xfoil.exe 失败并挂起时,双击批处理文件 XXX.bat ,cmd窗口将保留并显示如下:
enter image description here

如果 xfoil.exe 成功运行,批处理文件将自动运行并消失 .

4我很确定批处理文件没有被杀死,因为当我mannualy删除xfoil_batch_pid_11028.dat时,如果它失败了,它会输入到 xfoil.exe ,一条消息显示操作无法完成导致此文件已由windos cmd打开 .