calling one batch file mutiple times - python

I want to call a batch file from another batch file ten times.
I want to know is there anyway i can use looping in batch commands, something like while or for.
For now i was working on this
set _script_name=script1
echo %_script_name%
set num1=0
set num2=1
set terminator=5
SET _log_path=D:\USERS\Administrator\Desktop\batch_v2\Logs\
SET device1=4df1a5c715b65fb1
SET _monkey_path=D:\USERS\Administrator\Desktop\adt-bundle-windows-x86_64-20130729\sdk\tools\
cd %_monkey_path%
:loop
set /a num1= %num1% + %num2%
if %num1%==%terminator% goto close
goto open
:close
echo %num1%
pause
exit
:open
monkeyrunner.bat D:\USERS\Administrator\Desktop\batch_v2\script.py %device1% > %_log_path%newlog.txt
goto loop
I want to call script.py in a loop.
or is there any way i can use loop in my py file to call my batch file within while in the py file.
Basically my objectove is to use a batch file to pull logs after each iteration of my py script.
Using this script is called only once

Yes, there is a FOR construct in batch:
FOR /L %%G IN (1,1,100) DO (
START C:\path\to\your.bat
)
This code will run your bat file 100 times.
The syntax is FOR /L %%parameter IN (start,step,end) DO command
For more information check http://ss64.com/nt/for_l.html
If you want to run all your bats in parallel each in it's own console use START your.bat. If you want them to run in background use START /B your.bat. If you want them to run one after another and each in it's own console use START /WAIT your.bat.
The last option is to run them one after another AND all in your main console use CALL your.bat.

Related

Python: Check if Program is being closed

all.
Is there a way, using Python, to check if the script that is currently running is requested to close? For example, If I press the X-Button (close program button) on the top-right to close it, or end the script in any other way, can the script do some code before it ends? Example:
# script goes here...
if Script_To_Be_Closed: # replace this with an actual line of code.
do_stuff
There are multiple options you may use, like trapping keyboardinterrupts, but the simplest is atexit, which executes a function whenever a scripts is ended (except of a hard process kill indeed).
import atexit
def my_exit_function(some_argument):
// Your exit code goes here
print(some_argument)
if __name__ == '__main__':
atexit.register(my_exit_function, 'some argument', )
// Your script goes here
You can use a shell script to do the job
You can see the script command shown below which calls itself after executing the command to run the python file. once the python file is closed the next line will force the python command to run again. you can also customise the behaviour the way you want.
main.py
#!/bin/bash
python3 ./main.py
source ./infiniteRun.sh
If you need to stop the job just edit the file and remove the last line source ./infiniteRun.sh and save the file.

How can I stop a python script on a batch file

I want to start a python script and then automatically close that script after 2 minutes, run another command, and keep doing the same thing again like this (loop) forever :
Cd c:/location.of.script/
pythonscript.py
Stop (like ctrl+c) pythonscript.py after 120s
Del -f cookies.file
.
.
.
Is this even possible with a batch file on windows 10? If so, can someone please help me with this?
I’ve been looking everywhere but found nothing except the exit() command which stops the script from inside - this isn’t what I want to do.
You can change your python script to exit after 2 minutes, and you could batch file that has a while loop that runs forever and run the python script then deletes the cookie.file, I don't know if that's exactly what you want, but you can do it by putting a timer in your python script.
You can make a separate thread that keeps track of the time and terminates the code after some time.
An example of such a code could be:
import threading
def eternity(): # your method goes here
while True:
pass
t=threading.Thread(target=eternity) # create a thread running your function
t.start() # let it run using start (not run!)
t.join(3) # join it, with your timeout in seconds
And this code is copied from https://stackoverflow.com/a/30186772/4561068

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)

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.

Categories