82

How can I create a simple BAT file that will run my python script located at C:\somescript.py?

18 Answers 18

82
c:\python27\python.exe c:\somescript.py %*
Sign up to request clarification or add additional context in comments.

12 Comments

Hi MK- When I open Notepad, paste your line in there and save it and try to run it through windows scheduler, the commandline window opens for a split second and then closes. I'm not seeing a python27 folder in C:\ is that an issue?
Well, you do need to install python first. Go to www.python.org and download version 2.7
If you'd prefer to never have the command window show, you can use the pythonw executable by exchanging python.exe with pythonw.exe.
@alwbtc Are you calling your script as pythonw myscript.py or just ./myscript.py? If the latter, change the extension to .pyw and try again.
%* passes all arguments, %1 only the first one.
|
74

Open a command line (⊞ Win+R, cmd, ↵ Enter) and type python -V, ↵ Enter.

You should get a response back, something like Python 2.7.1.

If you do not, you may not have Python installed. Fix this first.

Once you have Python, your batch file should look like

@echo off
python c:\somescript.py %*
pause

This will keep the command window open after the script finishes, so you can see any errors or messages. Once you are happy with it you can remove the 'pause' line and the command window will close automatically when finished.

6 Comments

Thanks, but what does @echo offand %* mean?
@the_prole for @echo off take a look at -> technet.microsoft.com/en-us/library/… and %* can take any number of arguments.
hello. this answer is wrong. how do you know python's path is added to environment variables? this will not work if it is not.
python -i c:\somescript.py %* opens the python's interactive mode in the same environment after running the script, so you can inspect global variables for debugging.
@leshaan Saxena instead of pause you can add exit to close it
|
23

Here's how you can put both batch code and the python one in single file:

0<0# : ^
''' 
@echo off
echo batch code
python "%~f0" %*
exit /b 0
'''

print("python code")

the ''' respectively starts and ends python multi line comments.

0<0# : ^ is more interesting - due to redirection priority in batch it will be interpreted like :0<0# ^ by the batch script which is a label which execution will be not displayed on the screen. The caret at the end will escape the new line and second line will be attached to the first line.For python it will be 0<0 statement and a start of inline comment.

The credit goes to siberia-man

4 Comments

%~f0 should be in quotation marks: "%~f0", otherwise path with spaces or other special symbols will not be processed. To see this, call this file "My first script.bat" or places it in the folder "c:\My scripts".
Black autoformats to 0 < 0 # : ^ (giving The system cannot find the file specified.) otherwise nice hack!
@tejasvi88 are there any symbols after the ^? It should be the last symbol on the line. I've just checked this and it is still working.
@npocmaka It is working fine with 0<0# : ^ but not after formatting with Black. (which gives 0 < 0 # : ^)
14

Just simply open a batch file that contains this two lines in the same folder of your python script:

somescript.py
pause

3 Comments

is it possible to give the whole code, instead of the file name??
@RachitGupta somescript.py in above example is the filename of python script that you want to launch
@It'satrap Yes, see the answers by npocmaka, by Hans Ginzel, by Michael Villani and probably more, on this page.
7

You can use python code directly in batch file, https://gist.github.com/jadient/9849314.

@echo off & python -x "%~f0" %* & goto :eof
import sys
print("Hello World!")

See explanation, Python command line -x option.

2 Comments

How would you make the batch file pause once done? I can't add the pause anywhere.
You can do it in the python code as well, see How do I make python wait for a pressed key?
6

If you've added Python to your PATH then you can also simply run it like this.

python somescript.py

3 Comments

Yep that's an easy one, not so good if you have multiple Python installations (i.e 2.7 and 3.6 for example) also Python is almost always added to path so I don't think that's too much of a problem .
An option for that one is to make a copy in each of your python versions of the exe and rename to something unique. python2.7.exe, python3.6.exe etc. Then in the command line you can call it like python3.6 somescript.py
yes dreadfully obviously really but effective (why did I not think of that?). Also I think 36 be better than 3.6 and 27 for 2.7 the point might cause confusion.
4

--- xxx.bat ---

@echo off
set NAME1="Marc"
set NAME2="Travis"
py -u "CheckFile.py" %NAME1% %NAME2%
echo %ERRORLEVEL%
pause

--- yyy.py ---

import sys
import os
def names(f1,f2):

    print (f1)
    print (f2)
    res= True
    if f1 == "Travis":
         res= False
    return res

if __name__ == "__main__":
     a = sys.argv[1]
     b = sys.argv[2]
     c = names(a, b) 
     if c:
        sys.exit(1)
    else:
        sys.exit(0)        

Comments

3

Similar to npocmaka's solution, if you are having more than one line of batch code in your batch file besides the python code, check this out: http://lallouslab.net/2017/06/12/batchography-embedding-python-scripts-in-your-batch-file-script/

@echo off
rem = """
echo some batch commands
echo another batch command
python -x "%~f0" %*
echo some more batch commands
goto :eof

"""
# Anything here is interpreted by Python
import platform
import sys
print("Hello world from Python %s!\n" % platform.python_version())
print("The passed arguments are: %s" % sys.argv[1:])

What this code does is it runs itself as a python file by putting all the batch code into a multiline string. The beginning of this string is in a variable called rem, to make the batch code read it as a comment. The first line containing @echo off is ignored in the python code because of the -x parameter.

it is important to mention that if you want to use \ in your batch code, for example in a file path, you'll have to use r"""...""" to surround it to use it as a raw string without escape sequences.

@echo off
rem = r"""
...
"""

1 Comment

It even allows auto installing python if it doesn't exist. Yay!
2

This is the syntax: "python.exe path""python script path"pause

"C:\Users\hp\AppData\Local\Programs\Python\Python37\python.exe" "D:\TS_V1\TS_V2.py"
pause

Basically what will be happening the screen will appear for seconds and then go off take care of these 2 things:

  1. While saving the file you give extension as bat file but save it as a txt file and not all files and Encoding ANSI
  2. If the program still doesn't run save the batch file and the python script in same folder and specify the path of this folder in Environment Variables.

Comments

1

If this is a BAT file in a different directory than the current directory, you may see an error like "python: can't open file 'somescript.py': [Errno 2] No such file or directory". This can be fixed by specifying an absolute path to the BAT file using %~dp0 (the drive letter and path of that batch file).

@echo off
python %~dp0\somescript.py %*

(This way you can ignore the c:\ or whatever, because perhaps you may want to move this script)

Comments

0

Use any text editor and save the following code as runit.bat

@echo off
title Execute Python [NarendraDwivedi.Org]
:main
echo.
set/p filename=File Name :
echo. 
%filename%
goto main

Now place this file in the folder where python script is present. Run this file and enter python script's file name to run python program using batch file (cmd)

Reference : Narendra Dwivedi - How To Run Python Using Batch File

Comments

0

Create an empty file and name it "run.bat"

In my case i use "py" because it's more convenient, try:

C:
cd C:\Users\user\Downloads\python_script_path
py your_script.py

Comments

0
@echo off
call C:\Users\[user]\Anaconda3\condabin\conda activate base
"C:\Users\[user]\Anaconda3\python.exe" "C:\folder\[script].py"

Comments

0

could not see that anyone does it the same way that i do it so heres my way:)

note: the " is suppose to be there. Only replace the script.py.

@echo off
python "script.py"
pause

If you dont want to have the .bat file located in the same directory. Do something like the following. Note, this will make the script run in the directory where the .bat is located so if your script for example creates files in its running directory this may cause some wierdness.

@echo off
python "B:\my directory\with things in it\script.py"
pause

If you would like for your script to create one of these files automatically as i like to do it. I put something like the following in my scripts most the time.

import os
    f = os.listdir()

if "Start.bat" not in f:
    s = open("Start.bat", "w")
    s.write("@echo off" + "\n")
    s.write("python \"Script.py\"" + "\n")
    s.write("pause")
    s.close()

If it dosent work, make sure python is added to your PATH. Test it by opening the command prompt and enter python.

Heres some tutorial i found online on how to do that: Add path tutorial

Comments

-1
ECHO OFF
set SCRIPT_DRIVE = %1
set SCRIPT_DIRECTORY = %2
%SCRIPT_DRIVE%
cd %SCRIPT_DRIVE%%SCRIPT_DIRECTORY%
python yourscript.py`

1 Comment

Please explain what your script does. It's a lot easier to read that way.
-1

i did this and works: i have my project in D: and my batch file is in the desktop, if u have it in the same drive just ignore the first line and change de D directory in the second line

in the second line change the folder of the file, put your folder

in the third line change the name of the file

D: cd D:\python_proyects\example_folder\ python example_file.py

Comments

-1

Adding python to system PATH temporarily may help:

rem path to the Python installation folder
set Python=F:\python311

rem add Python path to environment path
set PATH=%Python%;%PATH%

rem run the Python script
python C:\somescript.py

2 Comments

Do NOT mess with the %PATH% if you don't exactly know, what you do. Above code might get you into trouble.
Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient. Can you kindly edit your answer to offer an explanation?
-2

start xxx.py

You can use this for some other file types.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.