Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed python code in batch script

In bash, we can:

python - << EOF
import os
print 'hello'
EOF

to embed python code snippet in bash script.

But in Windows batch, this doesn't work - although I can still use python -c but that requires me to collpase my code into one line, which is something I try to avoid.

Is there a way to achieve this in batch script?

Thanks.

like image 289
Baiyan Huang Avatar asked Jul 04 '13 10:07

Baiyan Huang


People also ask

What does %% mean in batch script?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

What does @echo off do?

The ECHO-ON and ECHO-OFF commands are used to enable and disable the echoing, or displaying on the screen, of characters entered at the keyboard. If echoing is disabled, input will not appear on the terminal screen as it is typed. By default, echoing is enabled.


2 Answers

You could use a hybrid technic, this solution works also with an python import.

1>2# : ^
'''
@echo off
echo normal 
echo batch code
echo Switch to python
python "%~f0"
exit /b
rem ^
'''
print "This is Python code"

The batch code is in a multiline string ''' so this is invisible for python.
The batch parser doesn't see the python code, as it exits before.

The first line is the key.
It is valid for batch as also for python!
In python it's only a senseless compare 1>2 without output, the rest of the line is a comment by the #.

For batch 1>2# is a redirection of stream 1 to the file 2#.
The command is a colon : this indicates a label and labeled lines are never printed.
Then the last caret simply append the next line to the label line, so batch doesn't see the ''' line.

like image 188
jeb Avatar answered Sep 30 '22 11:09

jeb


For a simple command: Windows cmd prompt only understands double quotes so you can triple them for this to work with -c option:

python -c print("""Hi""")

or use simple quotes which aren't interpreted at all by windows cmd:

python -c print('Hi')
like image 31
Jean-François Fabre Avatar answered Sep 30 '22 09:09

Jean-François Fabre