57

Is it possible to execute python commands passed as strings using python -c? can someone give an example.

honeybadger
  • 1,465
  • 1
  • 19
  • 32

2 Answers2

68

You can use -c to get Python to execute a string. For example:

python3 -c "print(5)"

However, there doesn't seem to be a way to use escape characters (e.g. \n). So, if you need them, use a pipe from echo -e or printf instead. For example:

$ printf "import sys\nprint(sys.path)" | python3

Kevin
  • 1,870
  • 2
  • 20
  • 22
  • 16
    `python3 -c "import sys; print(sys.path)"` is simpler. – mattmc3 Jul 20 '16 at 22:15
  • 4
    @mattmc3 You can't end a block (where indentation would decrease) with a semicolon. So it's more limited; you can't, for example, create a function and then actually call it, or use an if-else, or even an if followed by unconditional code. But (where possible) that is simpler. – Kevin Jul 23 '16 at 22:01
30

For a single string you can use python -c. But for strings as the question asks, you must pass them to stdin:

$ python << EOF
> import sys
> print sys.version
> EOF
2.7.3 (default, Apr 13 2012, 20:16:59) 
[GCC 4.6.3 20120306 (Red Hat 4.6.3-2)]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358