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.
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.
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.
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.
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')
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