Making Python batch files
How can I create a bat file to run a python file, specifically c开发者_C百科ontaining pygame.
Simple.
Just put the following as the very first line of the batch file:
python -x %0 %* &goto :eof
The rest of the batch file is the Python program. Here is a complete example:
python -x %0 %* &goto :eof
import sys
print "this is a batch file"
sys.exit()
First of all the & is a delimiter and allows the first line to contain two separate batch commands. The first one runs Python and the second command skips over the rest of the batch file which is Python code, not batch language.
The -x
is a Python option which skips the first line of the file, therefore this special line is only processed as a batch file, and not by the Python interpreter. %0
and %*
are two special batch file variables that represent the name of the batch file itself and any arguments given on the line when the batch file was invoked.
I have tried this as bot a .bat
and a .cmd
file and the only caveat is that you need to invoke the file with the full name including the extension. See a similar question on how to use Jscript in batch files.
All a bat file is is a plain text file (I mean PLAIN text, not MS word) with a list of commands.
For example, if you would open your game from the command line like this:
python MyGame.py
Then all you have to do is create a file containing exactly that. Change the extension to .bat
and you're done.
Just create a batch that contains this two lines:
"yourfilename".py
pause
Type command to cd
the directory, e.g. cd c:/users/me/Desktop
.
Then on the next line type mygame.py
.
Your code should look like:
cd c:/users/me/Desktop
mygame.py
精彩评论