Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a batch file execute commands within a python shell?

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.

like image 272
rafaelcosman Avatar asked Jan 25 '26 03:01

rafaelcosman


2 Answers

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.

like image 193
BDM Avatar answered Jan 26 '26 17:01

BDM


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.

like image 35
Bear Avatar answered Jan 26 '26 18:01

Bear