How can I create a simple BAT file that will run my python script located at C:\somescript.py?
18 Answers
c:\python27\python.exe c:\somescript.py %*
12 Comments
python.exe with pythonw.exe.pythonw myscript.py or just ./myscript.py? If the latter, change the extension to .pyw and try again.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
@echo offand %* mean?@echo off take a look at -> technet.microsoft.com/en-us/library/… and %* can take any number of arguments.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.exit to close itHere'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".0 < 0 # : ^ (giving The system cannot find the file specified.) otherwise nice hack!^? It should be the last symbol on the line. I've just checked this and it is still working.0<0# : ^ but not after formatting with Black. (which gives 0 < 0 # : ^)Just simply open a batch file that contains this two lines in the same folder of your python script:
somescript.py
pause
3 Comments
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
If you've added Python to your PATH then you can also simply run it like this.
python somescript.py
3 Comments
--- 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
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
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:
- While saving the file you give extension as bat file but save it as a txt file and not all files and Encoding ANSI
- 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
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
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
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
ECHO OFF
set SCRIPT_DRIVE = %1
set SCRIPT_DIRECTORY = %2
%SCRIPT_DRIVE%
cd %SCRIPT_DRIVE%%SCRIPT_DIRECTORY%
python yourscript.py`
1 Comment
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
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
%PATH% if you don't exactly know, what you do. Above code might get you into trouble.