Oliver
Oliver

Reputation: 101

BAT code: how to access a directory and run Python script

I am trying to create a .bat file that will run automatically during a startup on my server. I want the .bat file to open CMD, go to a given directory and then run a Python script from there.

Once the Python script has been activated, I want a separate CMD window to run a shutdown timer so that after a given time (t=86400, daily) the system will reboot. This is my way of making sure the file will continue to run after I disconnect to my server.

My current code is

@echo off
start cmd /k cd C:/Users/Administrator/Documents/
python scraperv2.py
start cmd /k shutdown -t 86400 -r -f

This code will go to the directory C:/Users/Administrator/Documents but it will not run the Python script. Please note that Python is set as a PATH variable.

What do I need to do to get this script to work?

Upvotes: 0

Views: 4593

Answers (2)

FatalBulletHit
FatalBulletHit

Reputation: 842

This should work now:

@ECHO OFF
START CMD /K "CD C:/Users/Administrator/Documents && python scraperv2.py"
START CMD /K "SHUTDOWN /R /F /T 86400"

Upvotes: -1

user7818749
user7818749

Reputation:

Ensure that you are able to run python from cmdline using any path to make sure it is actually in your environment, then simply do:

@echo off
python "C:\Users\Administrator\Documents\scraperv2.py" && shutdown /r /f /t 86400

Which will call python and the script from directory and if successful (%errorlevel%==0), it will do shutdown command. If %errorlevel% is anything other than 0 it will not run the shutdown command.

If you really want to do the cd then simply do this:

@echo off
cd /d "C:\Users\Administrator\Documents"
python scraperv2.py && shutdown /r /f /t 86400

Upvotes: 2

Related Questions