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?
One option to work around this limitation is to specify the command with the
$'string'
format using the newline escape sequence\n
.Note: this is supported by shells such as bash and zsh, but is not valid POSIX sh.
As mentioned by @slaadvak, there are some other workarounds here: Executing Python multi-line statements in the one-line command-line
The problem isn't with the import statement specifically, its that you have anything before a control flow statement. This won't work, either:
According to the Python reference (https://docs.python.org/2/reference/compound_stmts.html), ';' can only be used to combine "simple statements" together. In this case you're combining the simple statement
import re
, withif True:
.if True
isn't a simple statement, because it's introducing flow control, and is therefore a compound statement. At least that's how I interpret the documentation.Here's the full text from the Python reference:
Python grammar might forbid
small_stmt ';' compound_stmt
.-c
argument is probably is interpreted asfile_input
:Note: there is a newline at the end of
simple_stmt
.if_stmt
is notsmall_stmt
it can't follow anothersmall_stmt
after';'
. A newline is necessary to introducecompound_stmt
aftersmall_stmt
.It is not an issue because
bash
allows multiline arguments, just don't close the opening single quote until you done e.g.:Note:
>
are printed by the shell itself here. It is not entered by hand.You can embed newlines directly in the argument.