62

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

0

2 Answers 2

78

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

Sign up to request clarification or add additional context in comments.

3 Comments

python3 -c "import sys; print(sys.path)" is simpler.
@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.
I don't understand the remark about escape characters here. They seem to work completely fine and as I would expect them to. (Do you just mean to say that you can't write the two-character sequence \n instead of a newline character to separate two statements in the script you pass to -c? Sure, you indeed can't do that, but why would you expect that to work?)
33

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)]

3 Comments

I found the answer. just copy paste this on the terminal. python -c "import sys; x = 'hello world'; print x;"
That's a string. If you want strings then you need to feed them to stdin.
I don't understand what this answer is trying to say. As far as I can tell there's no behaviour difference between piping a script into stdin or passing it as a -c argument. The only guess I had at what you might mean was that perhaps Python would execute commands as it receives them on stdin - but nope, it seems it waits for the end of stdin and then executes the received script. So what do you mean?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.