如何在使用 subprocess.Popen 函数后暂停 cmd window

How to pause cmd window after using subprocess.Popen function

我想让 5 个子流程同时工作。问题是 cmd window 出现了一瞬间,所以我看不到任何东西。我怎样才能暂停它或做任何其他事情才能在完成代码后看到 window?

我是这样打开的:

client = subprocess.Popen(f'python file.py {arg1} {arg2}', creationflags=CREATE_NEW_CONSOLE)

您可以创建 Windows 批处理文件来执行您的 Python 脚本,然后在结束前暂停。

import atexit
import msvcrt
import os
import subprocess
import sys
from tempfile import NamedTemporaryFile
import time
import textwrap


def create_batchfile(proc_no, py_script_filename, *script_args):
    """Create a batch file to execute a Python script and pass it the specified
    arguments then pause and wait for a key to be pressed before allowing the
    console window to close.
    """
    with NamedTemporaryFile('w', delete=False, newline='', suffix='.bat',
                           ) as batchfile:
        cmd = (f'"{sys.executable}" "{py_script_filename}" ' +
               ' '.join(f'"{sarg}"' for sarg in script_args))

        print(f'{cmd}')  # Display subprocess being executed. (optional)
        batchfile.write(textwrap.dedent(f"""\
            @echo off
            title Subprocess #{proc_no}
            {cmd}
            echo {py_script_filename} has finished execution
            pause
        """))
        return batchfile.name


def clean_up(filenames):
    """Remove list of files."""
    for filename in filenames:
        os.remove(filename)


temp_files = []  # List of files to delete when script finishes.
py_script_filename = 'my_file.py'

atexit.register(clean_up, temp_files)

for i in range(1, 4):
    batch_filename = create_batchfile(i, 'my_file.py', i, 'arg 2')
    temp_files.append(batch_filename)
    subprocess.Popen(batch_filename, creationflags=subprocess.CREATE_NEW_CONSOLE)

print('Press any key to quit: ', end='', flush=True)
while True:  # Wait for keypress.
    if msvcrt.kbhit():
        ch = msvcrt.getch()
        if ch in b'\x00\xe0':  # Arrow or function key prefix?
            ch = msvcrt.getch()  # Second call returns the actual key code.
        break
    time.sleep(0.1)