Sequentially running multiple python programs "with sys" using batch - python

I am using Windows based PC.
I have multiple python programs with "sys". I mean the programs have these lines.
import sys
input_file = sys.argv[1]
output_file = sys.argv[2]
So I run these programs by running
python program1.py input1 output1
However, there are series of python programs so it will be convenient if I can run all these by double-clicking only one file.
How can I run them all sequentially, not simultaneously?
I tried things like
start C:\python27\python.exe program1.py input1 output1
start C:\python27\python.exe program2.py input2 output2
But it did not work..

Call is mainly for calling a batch file from within a batch file or running a block in current batch file as subroutine.
Start is the command to start any application as a separate process which means for a console applications to run it in a separate command prompt (console) window. A GUI application executed from within a batch file is always started as a separate process even if command start is not used.
Running an application results in halting the execution of the batch file until the application terminates itself for most applications. (There are applications with a different behavior caused by the application itself.) But a console or GUI application started using command start results in immediate continuation of batch file execution.
With using start /wait ... it is possible to start a console or GUI application as a separate process and halt execution of the batch file until the application terminates itself.
start /wait C:\python27\python.exe program1.py input1 output1
start /wait C:\python27\python.exe program2.py input2 output2
On running start /? in a command prompt window, the help for this command is printed into the output window.
["title"] means that optionally a title can be set for the new command prompt window (used only on starting a console application). I mention this here because command start can interpret any string in double quotes anywhere on the command line also as window title. Therefore if the application to start or one of its parameters must be enclosed in double quotes because of a space character or one of these characters &()[]{}^=;!'+,`~ in path or file name, it is better to explicitly specify a title string in double quotes immediately after command start as first parameter which can be even an empty string like "" (best for GUI applications).
start "Python Task 1" /wait "C:\python27\python.exe" program1.py input1 output1
start "Python Task 2" /wait "C:\python27\python.exe" program2.py input2 output2

import os
os.system('python' + ' ' + 'python_1.py')
os.system('python' + ' ' + 'python_2.py')
This solution is itself a python program. You can also construct the program names and have this in a loop. You can also add a parameter after the program name.

Related

Call to several batch files through CMD doesn't block

I'm trying to call several install.bat files one after another with Python trough CMD.
It is necessary that each bat file be displayed in an interactive console window because it asks for some users instructions and that the python program only resume after each CMD process is resolved
Each install.bat file can take a pretty long time to finish its process.
My code is the following :
for game in games :
print("----------- Starting conversion for %s -----------" %game)
subprocess.call("start cmd /C " + "Install.bat", cwd=os.path.join(gamesDosDir,game), shell=True)
print("end")
But the console windows inside the shell are launched all at once and the "end" message appears event before any of them is finished, whereas I would like them appearing one by one and not go to the n+1 one until the n one is finished and the console window closed (either by user or automatically /K or /C then).
I understand this is some problems using CMD as call should be blocking. How to resolve that? Additionally, if possible how to keep it exactly the same and add 'Y' and 'Y' as default user input?
The most common way to start a batch file (or more generally a CLI command) if to pass it as an argument to cmd /c. After you comment I can assume that you need to use start to force the creation of a (new) command window.
In that case the correct way is to add the /wait option to the start command: it will force the start command to wait the end of its subprocess:
subprocess.call("start /W cmd /C " + "Install.bat", cwd=os.path.join(gamesDosDir,game),
shell=True)
But #eryksun proposed a far cleaner way. On Windows, .bat files can be executed without shell = True, and creationflags=CREATE_NEW_CONSOLE is enough to ensure a new console is created. So above line could simply become:
subprocess.call("Install.bat", cwd=os.path.join(gamesDosDir,game),
creationflags = subprocess.CREATE_NEW_CONSOLE)

Run two parallel cmd from single batch file ?

I want to run two python files from a batch file in parallel I want each one to be executed in a separate cmd because they take time to finish and I want them to run in parallel is there away to do it ?
start runs your script in a new shell.
start "" script1.py
script2.py
runs them in parallel, but note that there is no (easy) way to resynchronize, ie. wait in the calling batch for script1.py to complete.
(the empty quotes after start are for an optional window title argument to start, if you omit them and enclose your script path in quotes because it contains spaces, then start would take that erroneously as window title)

subprocess window disappear quickly

In python, I use subprocess.Popen() to launch several processes, I want to debug those processes, but the windows of those processes disappeared quickly and I got no chance to see the error message. I would like to know whether there is any way I can stop the window from disappearing or write the contents in the windows to a file so that I can see the error message later.
Thanks in advance!
you can use the stdout and stderr arguments to write the outputs in a file.
example:
with open("log.txt", 'a') as log:
proc = subprocess.Popen(['cmd', 'args'], stdout=log, stderr=log)
In windows, the common way of keeping cmd windows opened after the end of a console process is to use cmd /k
Example : in a cmd window, typing start cmd /k echo foo
opens a new window (per start)
displays the output foo
leave the command window opened

Closing console application after completion from Python

I have an exe file that I have to call with several parameters, and for this purpose I use a bat file. After I execute bat file command prompt does not close, but wait for me to press a key. Now I have to run this exe several times, and for this I want to run a script that will do it for me.
i = 0
for path in Paths
outout = codecs.open('runExe.bat', 'w')
output.write(PathToExe + " -param1" + " -param2 " + param2Val[0] + " -param3 " + param3Val[0] + " -param4 " + param4Val[0] + " -param5 param5Val")
output.close()
subprocess.call(["regsvr32.exe", path, "-u", "-s"])
subprocess.call(["regsvr32.exe", path, "-s"])
subprocess.call("runExe.bat")
i + = 1
where param3Val, param4Val, param5Val are lists with values for related command prompt parameters.
When I call this bat file, everything works perfectly for the first fun of exe, but after it executes, command promt waits for my respond. When I press any key, it closes and then exe file starts with different parameters.
So I want to eliminate with key-pressing thing. I tried to put "exit" to the end of the bat file, but it did not work. How can I close command prompt window from script, when exe finishes working?
Thanks in advance!
Upd1: sarmold's way of doing thing works fine, but I think this it is exe (console application) that is waiting for my response. Smth in exe file prevents console window from closing, but I do not have access to sources. How can I close it's window after it executes?
Upd2: I have tried to add "shell" call after subprocess.call, but this does not seem to work either, still have to respond to the console manually :(
shell = win32com.client.Dispatch("WScript.Shell")
shell.AppActivate("Command Prompt")
shell.SendKeys("cls(ENTER)")
There are two possible approaches here:
Make only a single bat file that contains all your commands, including the regsvr32.exe commands, and execute that.
Have the Python script do everything for you.
For the first approach, use the "a" open mode to append to the batch file. (Perhaps delete it at script start.) Write the contents of your three commands to the batch file within the loop -- so you wind up with a long batch file that includes all the commands you need.
Then call the subprocess.call() command once, outside the loop, at the end of the script, to run the entire thing.
For the second approach, remove all the batch-file writing and run your PathToExe using Python's subprocess.call(). It's almost as simple as deleting all lines that work with output, but change output.write() to subprocess.call() -- and obviously, fiddle with the contents a little bit so they work for subprocess.call() directly.
Are you running this in a way that launches a command prompt every time you run runExe.bat? It shouldn't necessarily wait for you to close the console, but since it does, try running your script with subprocess.call("cmd /C runExe.bat").
#Arnold is right, though: It's better to simplify your set-up and (imho) just let python handle everything.

Why does my script stop executing commands after calling an .EXE?

Here is the relevant code from a Python script where a few commands are executed to copy an executable file and then execute it:
exe_file_path = os.getcwd() + r'\name_of_executable.exe'
temp_loc = os.environ['temp']
subprocess.Popen(r'copy %s %s' % (exe_file_path, temp_loc), shell=True)
exe_file_path = os.environ['temp'] + r'\name_of_executable.exe'
subprocess.Popen(r'start %s' % (exe_file_path), shell=True)
subprocess.Popen(r'del %s' % (exe_file_path), shell=True)
Currently, name_of_executable.exe only prints out text and then calls system("pause").
After the pause is executed, I push enter and I would assume the executable would close and the Python script would continue, but the last line of Python doesn't execute.
Is this because I'm using the TEMP folder? (I'm executing from a command prompt running as administrator. How do I get the script to work?
All programs will be immediately started one after another. Call communicate on each Popen object to wait for program termination.
Additionally, your use of format strings is unnecessarily dangerous. ['copy', exe_file_path, temp_loc] automatically escapes any strange characters in exe_file_path and temp_loc (and is easier to read).
By the way, Python has very good functions for copying and deleting files in shutil and os; there is no need to call shell programs for that.
And instead of concatenating strings to determine exe_file_path, you should use os.path.join (although this is not that important, since your program seems locked to Windows).

Categories