Issue
Why do I receive a syntax error for the following one-liner Python code?
python -c 'import re; if True: print "HELLO";'
File "<string>", line 1
import re; if True: print "HELLO";
^
SyntaxError: invalid syntax
The following code works just fine:
python -c 'if True: print "HELLO";'
How can I change my one line to execute my intended script on a single line from the command line?
Solution
One option to work around this limitation is to specify the command with the $'string'
format using the newline escape sequence \n
.
python -c $'import re\nif True: print "HELLO";'
Note: this is supported by shells, such as Bash and Z shell (zsh
), but it is not valid POSIX Bourne shell (sh
).
As mentioned by slaadvak, there are some other workarounds here: Executing Python multi-line statements in the one-line command-line
Answered By - Rynant Answer Checked By - David Goodson (WPSolving Volunteer)