Is it possible to execute python commands passed as strings using python -c? can someone give an example.
Asked
Active
Viewed 5.1k times
57
-
1Can you share with us what you have tried so far? – Levon May 26 '12 at 18:02
-
actually, I was looking for how to use python -c "" format. – honeybadger Jun 08 '12 at 18:38
2 Answers
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
-
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
-
8I found the answer. just copy paste this on the terminal. python -c "import sys; x = 'hello world'; print x;" – honeybadger May 29 '12 at 14:25
-
That's *a* string. If you want *strings* then you need to feed them to stdin. – Ignacio Vazquez-Abrams May 29 '12 at 17:36