3

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.

2
  • You can run a specific program (file) from batch, but I'm not sure about command-line execution. Commented Apr 20, 2013 at 0:24
  • 1
    Yep. One really ugly way to do this might be to write a .py file and then run it. I'm hoping someone comes up with something better than that. Commented Apr 20, 2013 at 0:26

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey @Prof Pickle, I think it didn't work for you because of the -x flag. It causes the interpreter to skip the first line of the program to allow for non unix #! to be ignored. So without knowing more than what you posted I would assume that print "hello world" was just skipped as described.
1

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.

4 Comments

Thanks! That's beautifully simple.
You are welcome, I am not sure how much you need to do, but you can use semi-colons to chain statements together in the command string as well.
Yep. But it's awkward to put them all on one line.
True, I don't recommend writing whole programs that way but for some things it works perfectly. It is there for those simple situations where you just want to run something right away.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.