Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run function from the command line

I have this code:

def hello():     return 'Hi :)' 

How would I run this directly from the command line?

like image 819
Steven Avatar asked Oct 21 '10 11:10

Steven


People also ask

How do you run a function in Python 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!

How do I run a bash function in terminal?

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.


1 Answers

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()' 
like image 177
Frédéric Hamidi Avatar answered Sep 21 '22 15:09

Frédéric Hamidi