在一个 Windows 命令提示符下按顺序运行多个程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4415134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run multiple programs sequentially in one Windows command prompt?
提问by Sean
I need to run multiple programs one after the other and they each run in a console window. I want the console window to be visible, but a new window is created for each program. This is annoying because each window is opened in a new position from where the other is closed and steals focus when working in Eclipse.
我需要一个接一个地运行多个程序,并且每个程序都在一个控制台窗口中运行。我希望控制台窗口可见,但为每个程序创建了一个新窗口。这很烦人,因为在 Eclipse 中工作时,每个窗口都在另一个关闭的新位置打开并窃取焦点。
This is the initial code I was using:
这是我使用的初始代码:
def runCommand( self, cmd, instream=None, outstream=None, errstream=None ):
proc = subprocess.Popen( cmd, stdin=instream, stdout=outstream, stderr=errstream )
while True:
retcode = proc.poll()
if retcode == None:
if mAbortBuild:
proc.terminate()
return False
else:
time.sleep(1)
else:
if retcode == 0:
return True
else:
return False
I switched to opening a command prompt using 'cmd' when calling subprocess.Popen and then calling proc.stdin.write( b'program.exe\r\n' ). This seems to solve the one command window problem but now I can't tell when the first program is done and I can start the second. I want to stop and interrogate the log file from the first program before running the second program.
在调用 subprocess.Popen 然后调用 proc.stdin.write( b'program.exe\r\n' ) 时,我切换到使用 'cmd' 打开命令提示符。这似乎解决了一个命令窗口的问题,但现在我不知道第一个程序何时完成,我可以启动第二个程序。我想在运行第二个程序之前停止并查询第一个程序的日志文件。
Any tips on how I can achieve this? Is there another option for running the programs in one window I haven't found yet?
关于如何实现这一目标的任何提示?在我还没有找到的一个窗口中运行程序是否有另一种选择?
采纳答案by martineau
Since you're using Windows, you could just create a batch file listing each program you want to run which will all execute in a single console window. Since it's a batch script you can do things like put conditional statements in it as shown in the example.
由于您使用的是 Windows,您只需创建一个批处理文件,列出您想要运行的每个程序,这些程序都将在单个控制台窗口中执行。由于它是一个批处理脚本,您可以执行一些操作,例如将条件语句放入其中,如示例所示。
import os
import subprocess
import textwrap
# create a batch file with some commands in it
batch_filename = 'commands.bat'
with open(batch_filename, "wt") as batchfile:
batchfile.write(textwrap.dedent("""
python hello.py
if errorlevel 1 (
@echo non-zero exit code: %errorlevel% - terminating
exit
)
time /t
date /t
"""))
# execute the batch file as a separate process and echo its output
kwargs = dict(stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True)
with subprocess.Popen(batch_filename, **kwargs).stdout as output:
for line in output:
print line,
try: os.remove(batch_filename) # clean up
except os.error: pass
回答by Piotr Dobrogost
In section 17.5.3.1. Constantsin the subprocessmodule documentation there's descriptionof subprocess.CREATE_NEW_CONSOLE
constant:
在第17.5.3.1节中。常量将在子模块文档有描述的subprocess.CREATE_NEW_CONSOLE
常数:
The new process has a new console, instead of inheriting its parent's console (the default).
新进程有一个新的控制台,而不是继承其父级的控制台(默认)。
As we see, by default, new process inherits its parent's console. The reason you observe multiple consoles being opened is the fact that you call your scripts from within Eclipse, which itself does not have console so each subprocess creates its own console as there's no console it could inherit. If someone would like to simulate this behavior it's enough to run Python script which creates subprocesses using pythonw.exeinstead of python.exe. The difference between the two is that the former does not open a console whereas the latter does.
正如我们所见,默认情况下,新进程继承其父进程的控制台。您观察到多个控制台被打开的原因是您从 Eclipse 中调用脚本,Eclipse 本身没有控制台,因此每个子进程都会创建自己的控制台,因为它没有可以继承的控制台。如果有人想模拟这种行为,运行 Python 脚本就足够了,该脚本使用pythonw.exe而不是python.exe创建子进程。两者的区别在于前者不打开控制台,而后者打开。
The solution is to have helper script — let's call it launcher— which, by default, creates console and runs your programs in subprocesses. This way each program inherits one and the same console from its parent — the launcher. To run programs sequentially we use Popen.wait()
method.
解决方案是使用辅助脚本——我们称之为启动器——默认情况下,它会创建控制台并在子进程中运行您的程序。这样,每个程序都从其父级继承了一个相同的控制台 —启动器。为了顺序运行程序,我们使用Popen.wait()
方法。
--- script_run_from_eclipse.py ---
--- script_run_from_eclipse.py ---
import subprocess
import sys
subprocess.Popen([sys.executable, 'helper.py'])
--- helper.py ---
--- helper.py ---
import subprocess
programs = ['first_program.exe', 'second_program.exe']
for program in programs:
subprocess.Popen([program]).wait()
if input('Do you want to continue? (y/n): ').upper() == 'N':
break