Home >Backend Development >Python Tutorial >How to Execute Python Functions from the Command Line?
Executing Python Functions from the Command Line
When dealing with Python scripts, one may encounter the need to invoke specific functions from the command line. Here's how to achieve this for a function named hello():
<code class="python">def hello(): return 'Hi :)'</code>
To run this function directly from the command line, you can use the -c (command) argument in the following format:
$ python -c 'import foo; print foo.hello()'
Here, foo.py is the name of the file containing the hello() function.
Alternatively, if you disregard namespace pollution within the script:
$ python -c 'from foo import *; print hello()'
To strike a balance, you can import only the necessary function:
$ python -c 'from foo import hello; print hello()'
These methods allow for the seamless execution of Python functions from the command line, providing a convenient and versatile means of accessing code.
The above is the detailed content of How to Execute Python Functions from the Command Line?. For more information, please follow other related articles on the PHP Chinese website!