As shown (but not explained) in a couple of other answers,
and as documented in the Python 3.11.1 documentation
Command line and environment,
you can use -c command
:
-c command
Execute the Python code in command
.
command
can be one or more statements separated by newlines,
with significant leading whitespace as in normal module code.
In other words, you can put your entire Python script into a Bash string.
Here’s a slightly complicated / convoluted approach,
using command substitution and a here document:
#!/bin/bash
python3 -c "$(cat << EOF
a = input('?>')
print('you typed', a)
print('\033[1;32mbye...\033[m')
EOF
)"
This works.
The $()
(command substitution) passes the output of the command inside
(in this case cat
) as the argument to Python.
There is no pipelining so standard input can be used in the Python code.
This simpler approach (making the Python script a literal string)
also works:
#!/bin/bash
python3 -c "
a = input('?>')
print('you typed', a)
print('\033[1;32mbye...\033[m')"
This has the usual issue with double-quoted strings in Bash:
shell meta-characters "
, $
, `
and \
need to be escaped.
For example, if you need to use "
in your Python code,
you should escape it like this:
#!/bin/bash
python3 -c "
a = input('?>')
print(\"you typed\", a)
print(\"\033[1;32mbye...\033[m\")"
But why not just
change all the single quotes in your Python code to double quotes,
and put the entire Python script into single quotes?
#!/bin/bash
python3 -c '
a = input("?>")
print("you typed", a)
print("\033[1;32mbye...\033[m")'
Similarly,
$ python3 -c "print('An odd string:', '$((6*7))')"
An odd string: 42
$ python3 -c 'print("An odd string:", "$((6*7))")'
An odd string: $((6*7))
script.sh && python script.py
?import os
os.system ("./script.sh")
python -c $(cat << EOF ... ... EOF )"
More in my answer