簡體   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