繁体   English   中英

使用子进程后如何暂停cmd window.Popen function

[英]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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM