简体   繁体   English

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

[英]How to pause cmd window after using subprocess.Popen function

I want to make let's say 5 subprocesses to work in exact same time.我想让 5 个子流程同时工作。 Problem is cmd window that appears for a split second so I am unable to see anything.问题是 cmd window 出现了一秒钟,所以我看不到任何东西。 How can I pause it or make anything else to have that window on sight after finished code?在完成代码后,如何暂停它或做任何其他事情才能看到 window?

I am opening it with such approach:我用这样的方法打开它:

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

You could do it by creating Windows batch files that executed your Python script and then pause before ending.您可以通过创建 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