Can I use a batch file to start a python shell and execute commands? I know that
python
will start a python shell, but a batch file containing
python
1+1
will first run python, and then only when you quit python will it attempt to run 1+1. It will not execute any commands within the python shell.
After a little searching around, I managed to find this website that has a method to do this. As you will see on the website, all you need to do is:
@setlocal enabledelayedexpansion && python -x "%~f0" %* & exit /b !ERRORLEVEL!
#start python code here
print "hello world"
This didn't work for me, however I thought it might help.
I haven't been able to find any other source that says it's possible.
Just thought of something else that I haven't tested. I combined Bear's answer and mine.
@for /f "skip=1 delims=" %i in (%0) do @python -c "%i"
#Start Python here.
However, the other method should be used.
I know this has an accepted answer but you might also try the -c argument for the python command. python -c "print(1+1)" will print "2" to the console. The -c flag means "command" and is interpreted by python immediately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With