rafaelcosman
rafaelcosman

Reputation: 2599

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.

Upvotes: 3

Views: 1540

Answers (2)

BDM
BDM

Reputation: 3900

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.

Upvotes: 2

Bear
Bear

Reputation: 516

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.

Upvotes: 1

Related Questions