43

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?

2 Answers 2

40

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.

9
  • Thanks. I didn't know I need to quote using ''. Btw, how do I enter a newline?
    – Jason
    Commented Nov 26, 2014 at 19:52
  • 1
    @Jason The quotes are needed to prevent your shell from somehow interpreting / messing with your Python code. You enter a newline by pressing enter on your keyboard. Any terminal will input that as a newline if you types a quote first. Commented Nov 26, 2014 at 19:53
  • When I press enter it terminates my inputs and starts executing. Does it have anything to do with the platform or version? I'm using a Ubuntu with python 2.7
    – Jason
    Commented Nov 26, 2014 at 19:57
  • @Jason You might have forgotten to type a quote prior to typing enter. If not, please paste your terminal contents here. Commented Nov 26, 2014 at 19:58
  • Here is my terminal: srf10mwu@cru-13gx ~/scripts/tools: python -c 'print 10 Unmatched '. srf10mwu@cru-13gx ~/scripts/tools: python -c 'print 10' 10 srf10mwu@cru-13gx ~/scripts/tools:
    – Jason
    Commented Nov 26, 2014 at 20:00
20

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 ;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.