Python.exe stays open after running batch file in task scheduler - windows

I'm trying to schedule in task scheduler:
Run a batch file
Activate a conda environment
Run a python program
Exit command prompt
Everything works fine, except the python.exe window will remain open while the command prompt closes.
My batch file: (the sleep is for the python code to run. It takes a few seconds)
call activate python2
start C:\Users\Chris\Anaconda3\envs\python2\python.exe testtest.py
sleep 30
exit
My python script:
driver = webdriver.Chrome(executable_path="C:\path\to\chromedriver")
driver.get('http://website.com')
# Find email and pw fields and then fill them in
email = driver.find_element_by_id("user_email")
email.send_keys('myemail#email.com')
pw = driver.find_element_by_id("user_password")
pw.send_keys('password')
# Click on sign-in button
driver.find_element_by_class_name("button").click()
time.sleep(5)
# Click on save button to update
driver.find_element_by_class_name("button").click()
# Close driver
driver.close()
Last thing, the program/script is the batch file, no arguments, and the start in is in the directory that the batch file is in.
Any help would be appreciated!

put you python codes in a main() function.
and give:
if __name__ == '__main__':
main()
at the end.
Just tested works for me.

#pk2019 's answer really helped me.
One improvement is to use
drv = webdriver.Chrome()
# Do your things.
...
drv.close()
drv.quit()
No need to do the dirty work of killing task.

I'm not a python expert, but I think you just need to call sys.exit() or quit().
Instead of using sleep and waiting too long or possibly not long enough, call start with the wait option:
call activate python2
start /WAIT C:\Users\Chris\Anaconda3\envs\python2\python.exe testtest.py
exit
If you don't need the batch file to do anything else, you can just start the python script and exit.

I had a similar problem with a Python selenium web scraper running geckodriver.exe Firefox web driver on Windows (executed via Task Scheduler using a .bat file). The problem is that my geckodriver.exe process is still running after the Python script is done ... and I think that running process is preventing the Windows command prompt from closing.
In order to test this hunch, I inserted the tasklist command into the .bat file, both before and after the Python script. It prints out a list of running Windows tasks to the console ... I noticed the geckodriver.exe file was still running the Python script was finished.
The way to kill a Windows process (using taskkill) is described in these two different Stackoverflow responses:
Safely killing a python script on Windows
Batch script to close all open Command Prompt windows
How to close Command Prompt window after Batch file execution in python?
Here is the Windows documentation for taskkill:
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/taskkill
In my case, I added this as the 2nd to last line: taskkill /im geckodriver.exe /f, and the last line was exit. That worked.

Related

CMD doesn't wait to finish process

When i use command
<path exc.xlsx>
it starts excel file working and wait until i close the file than i can type next command. My issue is that when other excel file is running cmd doesn't wait to close the file and goes to next line. It is necessary to type the command that will force cmd to wait until i close excel file even when onother excel file is running. I tried a lot of commands from the internet but no one seems to work properly. These were for instance:
start /wait exc.xlsx && exit
exc.xlsx cmd /k
exc.xlsx|rem
I'm using Windows7.
I try this method but it sometimes doesn't work properly. The line <os.rename> try to change name of the file. If it can it means that the file is closed and break the loop but using that the script sometimes can't open the excel file. I'm not as advanced as i would be and cant find another way to check if the file is closed.
import os
def is_open(file_name):
if os.path.exists(file_name):
while True:
try:
os.rename(file_name, file_name)
break
except:
continue
time.sleep(0.001)
is_open('exc.xlsx')
That's not very dignified and uses a lot of processor. If there is a way using programing language (preferably python) I can implement that in my script.

How do I tell a windows batch script to execute the next line without waiting for the previous line to finish executing?

I'm setting up a .cmd script to be run on startup for a pseudo-server (It's actually a laptop, but that's irrelevant) to automatically launch pageant, load an SSH key, connect to an SSH server using Putty (Pageant would automatically authenticate with the key), then launch mIRC which in turn has a series of scripts setup to operate as an IRC bot and automatically connect to networks using putty as an SSH tunnel.
With that in mind, I have the below code in a startup.cmd file:
"C:\Program Files (x86)\PuTTY\pageant.exe" c:\Path\To\Private\Key.ppk
"C:\Program Files (x86)\PuTTY\putty.exe" -ssh user#host
"C:\Program Files (x86)\mIRC\mirc.exe"
EXIT
When I test run this file, the command prompt runs the first line, launches pageant, and then sits there and does nothing until I close pageant completely. I believe I have an idea on what the issue here is, but I can't find any information on how to resolve this in a batch file.
I do know on linux systems, if I were running a bash script to do something similar, I would want to have a & symbol at the end of each line to tell it to run the next command without waiting for the previous command to finish executing. I did try that in the batch script in the off chance that would work (It didn't).
For those who may ask, this is on Windows 8.1 64 bit. The user running this script is not an administrator.
I can't comment to expand on Squashman's suggestion, so let me answer here.
In your case, if you only want to have Pageant running in the background, without interacting with it, I think it's best to run:
START "" /B <your command>
The /B parameter will spawn the process without launching a new window for it, which seems like something you'd like to avoid (anyway, it's probably closest to the behaviour you can obtain in Linux with &).
Please note that if you close the window from which you spawned this process, it will terminate as well.

SVN update using windows task scheduler not working

I want to setup a windows cron job to update svn. I created a batch file with this step:
START TortoiseProc.exe /command:update /path:"C:\svn" /closeonend:0
and setup the task scheduler to run this daily. This svn requires a password which I want to enter each time rather than cache it. The batch file works as expected without any issues.
The task scheduler shows that the job was successfully executed. However, I don't get the GUI to enter the password, neither does the directory get updated. Also, when I tried to manually update the svn directory thereafter, it says that svn is locked.
Why is task scheduler reporting successful?
Why is svn getting locked?
Task scheduler reports success because START seems to return exit code 0. START only starts an application and exits. It doesn't wait until the started application has exited. The task scheduler never sees the exit code of TortoiseProc this way.
You can do this with START WAIT. Enter START /? in a CMD for more information.
You can also do this with CMD /K itself. Enter CMD /? in a CMD for more information.
But I don't think you need START or CMD at all. You can either run TortoiseProc directly or call it via a batch script. In the batch script you can add more debugging like echos and redirected output in files to see what happens.
Do not use TortoiseProc.exe for this task! Use Subversion command-line client (svn.exe). Read the docs:
Remember that TortoiseSVN is a GUI client, and this automation guide
shows you how to make the TortoiseSVN dialogs appear to collect user
input. If you want to write a script which requires no input, you
should use the official Subversion command line client instead.

how to make my console in python not to close?

I'm making a application in python from Windows. When I run it in the console, it stops, shows an error, and closes. I can't see the error becase its too fast, and I can't read it. I'm editing the code with IDLE (the program that came with python when I instaled it), and when I run it with the python shell, there are no errors. I would run it from IDLE, but when I use the console, it has more features.
I don't know why this is happening. I need your help.
Run the program from an already-open terminal. Open a command prompt and type:
python myscript.py
For that to work you need the python executable in your path. Just check on how to edit environment variables on windows, and add C:\PYTHON26 (or whatever directory you installed python to).When the program ends, it'll drop you back to the CMD windows prompt instead of closing the window.Add code to wait at the end of your script. Adding ...
raw_input()
... at the end of the script makes it wait for the ENTER key. That method is annoying because you have to modify the script, and have to remember removing it when you're done.
Run your program from a Windows command prompt. That will not automatically close when the program finishes.
If you run your program by double-clicking on the .py file icon, then Windows will close the window when your program finishes (whether it was successful or not).
Create a text file in the program directory i.e. wherever your script is located. Change the extension to .bat for example text.bat. Then edit the text file and write:
python main.exe
pause
Now you can run the program without typing into the command console by double clicking the bat file, and the console window will not close.

How to prevent batch file (.bat) from closing terminal when running commands?

On a Windows 7 machine if I run a PHPUnit Selenium command like this manually in the terminal:
phpunit --verbose --log-junit _selenium_tests\results\home.xml _selenium_tests\frontend\home.php
It spawns a browser and runs the test just fine. Then it outputs the following on the screen:
Time: 10 seconds, Memory: 3.50Mb
OK (1 test, 3 assertions)
And the terminal stays open.
Now if I copy and paste the exact command in an empty file and save it as test.bat and click it, it also runs the test. I can see the browser open and all tests run. Only problem is it closes the terminal prompt right after. So I can't see the above output.
An even bigger problem is, since it closes the terminal if I add more commands for other tests after that initial one they don't run.
I tried adding:
pause
at the end of the bat file but no luck, it still closes. Any idea how to prevent this and be able to run one command after another without the terminal ever closing?
Your question is similar to this one. Try using call in front of your command. If you run a .bat file from another .bat file and don't use call, control doesn't return to the first batch file, so pause doesn't get executed.
Try cmd /K phpunit --verbose --log-junit _selenium_tests\results\home.xml _selenium_tests\frontend\home.php
The /K option in cmd /K string Carries out the command specified by string but remains,see http://www.computerhope.com/cmd.htm
Also, I don't know the file type of the phpunit command you execute - I'm not familiar with selenium. If it is batch file (i.e. ends with .bat), you just can't call them from another batch file: everything below the call to the second batch file will never get executed.
You then need to use the CALL command. CALL Enables a user to execute a batch file from within another batch file, see http://www.computerhope.com/call.htm

Resources