python calling external programs without opening c

2020-07-26 10:53发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
Running a process in pythonw with Popen without a console
How do I eliminate Windows consoles from spawned processes in Python (2.7)?

I am using Python 2.7 and running the python scripts from within IDLE.

The commands I am executing are simple exe's that perform quick tasks. The issue I am having is every time the external commands are called from within Python a console is created and it flashes on my screen and takes focus, thus preventing me from using my PC while executing various scripts.

Examples of how I am calling them from within Python are as follows:

result = call(["Commands\Set.exe", str(i), ARG2])
check_output(["Commands\Read.exe", ARG2])

Searching for a solution I came across adding the following

shell=True

to make the following command

check_output(["Commands\Read.exe", ARG2], shell=True)

However I still get the console appear every time an external command is called

回答1:

There might be two issues here. First off, if your python scripts have the .pyw extension then they will be associated with pythonw which does not use a console*. However, you have shell=True, which generates a console*. You need to run the program and hide the console:

import subprocess
proc = subprocess.Popen('hello.py',  creationflags=subprocess.SW_HIDE, shell=True)
proc.wait()

*Pedantically, it's not a dos prompt, it is a console window. DOS - Disk Operating System - was an IBM mainframe OS. MS-DOS or PC-DOS command-line features were mirrored (with a lot of extra features) by cmd.exe (a Windows shell), which is a console program and so uses a console window. It's that console window you need to hide.



回答2:

You need to use startupinfo parameter of subprocess.Popen() class' constructor.

startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
subprocess.Popen(command, startupinfo=startupinfo)

You do not need shell=True if all you want is to hide console window; see this answer.