Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
943 views
in Technique[技术] by (71.8m points)

bash - If statements and one line python scripts from command line

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One option to work around this limitation is to specify the command with the $'string' format using the newline escape sequence .

python -c $'import re
if True: print "HELLO";'

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...