I have this code:
def hello(): return 'Hi :)'
How would I run this directly from the command line?
To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!
To invoke a bash function, simply use the function name. Commands between the curly braces are executed whenever the function is called in the shell script. The function definition must be placed before any calls to the function.
With the -c
(command) argument (assuming your file is named foo.py
):
$ python -c 'import foo; print foo.hello()'
Alternatively, if you don't care about namespace pollution:
$ python -c 'from foo import *; print hello()'
And the middle ground:
$ python -c 'from foo import hello; print hello()'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With