How to use the -c flag in python

Question:

I noticed in the python doc that there is a -c flag. Here is what python doc says:

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.

There is no example in the doc and I couldn’t figure out how to make this work, and also in what situations it may help.

Anyone have any clue?

Asked By: Jason

||

Answers:

Just pass regular Python code as the argument to the flag:

python -c 'print 1
print 2'

Import modules works, and blank lines are OK, too:

python -c '
import pprint
pprint.pprint(1)
'

When using this feature, just be mindful of shell quoting (and indentation), and keep in mind that if you’re using this outside of a few shell scripts, you might be doing it wrong.

Answered By: Thomas Orozco

Easiest example

python -c "print 'example'"

It is useful whenever your program has a single line of code, for example, list comprehensions, etc.

Another example can be

python -c "a='example';print a"

As you can see, multiple statements are separated by ;

Answered By: Bhargav Rao
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.