A_Newbie
A_Newbie

Reputation: 63

How do you execute python without providing a file name?

I am relatively new to python, so I was wondering if I could call upon python to read a string (or the code it needs to execute) from outside the interactive python shell, similar to how exec() works when within Python. Basically, I want to know if there is any method to have python read code from the command line or otherwise rather than having to save that code within a 'file.py' or another similar file. I want to avoid running this: python file.py as I hope to avoid needing a filename. I was looking around for a solution and found Execute python commands passed as strings in command line using python -c and Python - How do I pass a string into subprocess.Popen (using the stdin argument)?. The first answer seems to be what I might want, but I lack in the knowledge department of how to pass the string into stdin, so I would be grateful if someone could better explain that method if it is the correct answer. The second link was what I found when looking up about stdin, and looked promising, but upon execution I realized that, from my understanding, I still need some sort of file name for subprocess. I was planning to use this in order to be used in Jupyter Notebook, or any similar program so when I run one data cell, it is able to be executed in Python or return the error message, but to first do that I have to find out how to reference the language I want without needing a file name. Thank you for your time and consideration!

Upvotes: 2

Views: 1754

Answers (2)

seralouk
seralouk

Reputation: 33147

You can use the following:

python -c "my_var = 'my name is john';print(my_var)"

Note that

1) using ; you seperate the commands.

2) you need to use " " and inside to type the commands.

Upvotes: 1

Simon Hobbs
Simon Hobbs

Reputation: 1010

Its a bit unclear exactly what you want to to with this but here is hello world using the command option (-c) from the command line without piping it in. This just runs the string passed as if it was in the python interpreter or in a script.

python -c "print('hello world')"

If you really want to run code from stdin you could use something like this:

echo "for i in range(100):\n\tprint(i)" | python -c "import sys;print('hello world');exec(''.join([item for item in sys.stdin]))"

There is more on how to use the command line tool in the man page or in the python documentation.

Upvotes: 3

Related Questions