Home > Article > Backend Development > How Can I Execute Python Functions from the Command Line?
Executing Python Functions from the Command Line
Consider the following Python code:
<code class="python">def hello(): return 'Hi :)'</code>
Executing this function directly from the command line offers several options.
Using the -c Argument
Utilize the -c (command) argument to directly execute the function. Assuming the script is named foo.py, run the following:
<code class="bash">$ python -c 'import foo; print foo.hello()'</code>
Simple Namespace Pollution
For simplicity, bypass namespace pollution by using this command:
<code class="bash">$ python -c 'from foo import *; print hello()'</code>
Controlled Namespace Pollution
For a controlled approach, import the specific function needed:
<code class="bash">$ python -c 'from foo import hello; print hello()'</code>
These methods provide flexibility in executing Python functions directly from the command line, allowing for efficient code execution in various scenarios.
The above is the detailed content of How Can I Execute Python Functions from the Command Line?. For more information, please follow other related articles on the PHP Chinese website!