I have this code:

def hello():
    return 'Hi :)'

How would I run this directly from the command line?

  • 16
    Probably you meant print "Hi :)" instead of return 'Hi :)'. – Tamás Oct 21 '10 at 11:56

15 Answers 15


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()'
  • 21
    I noted that on windows shell, you need a double quote instead of single. $python -c "import foo;foo.hello()" – Arindam Roychowdhury Jun 1 '16 at 12:59
  • 5
    What if the file is not in the local directory or on the PYTHONPATH? – Konstantin Jul 7 '17 at 14:32
  • On Ubuntu Linux you also have to use double quotes if you run the command from inside a Qt app for example. – Olaf Japp Jul 17 '17 at 11:52
  • 1
    The second one is a more general answer. I have a script defined multiple customer functions, and only call one depending on my need – xappppp Apr 15 '18 at 4:16

Just put hello() somewhere below the function and it will execute when you do python your_file.py

For a neater solution you can use this:

if __name__ == '__main__':

That way the function will only be executed if you run the file, not when you import the file.

  • 5
    this should be the correct answer – zon7 Nov 8 '17 at 11:41
  • 2
    And what if hello() takes arguments that should be supplied by the command line? – Anonymous Feb 10 '18 at 2:29
  • In that case you can send sys.argv to the method. Or access it from the hello method – Wolph Feb 10 '18 at 8:48
  • 1
    One difference between this answer and the import foo solution is that import foo allows calling an arbitrary function in foo without modifying foo. – plafratt Apr 26 '18 at 15:37
  • That's true, but I wouldn't recommend that solution beyond test purposes – Wolph Apr 26 '18 at 20:12

python -c 'from myfile import hello; hello()' where myfile must be replaced with the basename of your Python script. (E.g., myfile.py becomes myfile).

However, if hello() is your "permanent" main entry point in your Python script, then the usual way to do this is as follows:

def hello():
    print "Hi :)"

if __name__ == "__main__":

This allows you to execute the script simply by running python myfile.py or python -m myfile.

Some explanation here: __name__ is a special Python variable that holds the name of the module currently being executed, except when the module is started from the command line, in which case it becomes "__main__".

  • 1
    What is the difference between python -m foo -c 'foo.bar()' and python -c 'import foo; foo.bar()'? I get different behavior where it seems the -c argument is ignored in the first case. – Abram Jun 17 '17 at 7:56

I wrote a quick little Python script that is callable from a bash command line. It takes the name of the module, class and method you want to call and the parameters you want to pass. I call it PyRun and left off the .py extension and made it executable with chmod +x PyRun so that I can just call it quickly as follow:

./PyRun PyTest.ClassName.Method1 Param1

Save this in a file called PyRun

#!/usr/bin/env python
#make executable in bash chmod +x PyRun

import sys
import inspect
import importlib
import os

if __name__ == "__main__":
    cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
    if cmd_folder not in sys.path:
        sys.path.insert(0, cmd_folder)

    # get the second argument from the command line      
    methodname = sys.argv[1]

    # split this into module, class and function name
    modulename, classname, funcname = methodname.split(".")

    # get pointers to the objects based on the string names
    themodule = importlib.import_module(modulename)
    theclass = getattr(themodule, classname)
    thefunc = getattr(theclass, funcname)

    # pass all the parameters from the third until the end of 
    # what the function needs & ignore the rest
    args = inspect.getargspec(thefunc)
    z = len(args[0]) + 2

Here is a sample module to show how it works. This is saved in a file called PyTest.py:

class SomeClass:
 def First():
     print "First"

 def Second(x):
    # for x1 in x:
    #     print x1

 def Third(x, y):
     print x
     print y

class OtherClass:
    def Uno():

Try running these examples:

./PyRun PyTest.SomeClass.First
./PyRun PyTest.SomeClass.Second Hello
./PyRun PyTest.SomeClass.Third Hello World
./PyRun PyTest.OtherClass.Uno
./PyRun PyTest.SomeClass.Second "Hello"
./PyRun PyTest.SomeClass.Second \(Hello, World\)

Note the last example of escaping the parentheses to pass in a tuple as the only parameter to the Second method.

If you pass too few parameters for what the method needs you get an error. If you pass too many, it ignores the extras. The module must be in the current working folder, put PyRun can be anywhere in your path.

  • 2
    It's nice, but it's not really an answer to the question. – Francis Colas Mar 18 '15 at 19:31
  • 10
    I beg to differ; it is exactly the question. He asked how do you run a function from a file and that is exactly what this does. – Joseph Gagliardo Mar 20 '15 at 0:56
  • Can you explain what the bit about cmd_folder is doing? – RyanDay Jan 26 '18 at 22:44

add this snippet to the bottom of your script

def myfunction():

if __name__ == '__main__':

You can now call your function by running

python myscript.py myfunction

This works because you are passing the command line argument (a string of the function's name) into locals, a dictionary with a current local symbol table. The parantheses at the end will make the function be called.

update: if you would like the function to accept a parameter from the command line, you can pass in sys.argv[2] like this:

def myfunction(mystring):
    print mystring

if __name__ == '__main__':

This way, running python myscript.py myfunction "hello" will output hello.

  • Is it possible for this method to accept a parameter for the function? Such as myfunction(12) – Major Major Apr 18 at 2:49
  • @MajorMajor I have updated the answer to include how to do this – Noam Hacker Apr 18 at 14:10

If you install the runp package with pip install runp its a matter of running:

runp myfile.py hello

You can find the repository at: https://github.com/vascop/runp


Interestingly enough, if the goal was to print to the command line console or perform some other minute python operation, you can pipe input into the python interpreter like so:

echo print("hi:)") | python

as well as pipe files..

python < foo.py

*Note that the extension does not have to be .py for the second to work. **Also note that for bash you may need to escape the characters

echo print\(\"hi:\)\"\) | python
  • Considering the foo.py with hello() example, this is how one can use it with above idea. echo import foo;foo.hello() | python – Arindam Roychowdhury May 31 '16 at 9:27
  • Is there any way to pass in command-line arguments with this method? – iamseiko Apr 12 '17 at 18:46
  • FWIW, the following is slightly cleaner for the third example: echo 'print("hi:)")' | python – user3166580 Aug 31 '17 at 11:09

Let's make this a little easier on ourselves and just use a module...

Try: pip install compago

Then write:

import compago
app = compago.Application()

def hello():
    print "hi there!"

def goodbye():
    print "see ya later."

if __name__ == "__main__":

Then use like so:

$ python test.py hello
hi there!

$ python test.py goodbye
see ya later.

Note: There's a bug in Python 3 at the moment, but works great with Python 2.

Edit: An even better option, in my opinion is the module fire by Google which makes it easy to also pass function arguments. It is installed with pip install fire. From their GitHub:

Here's a simple example.

import fire

class Calculator(object):
  """A simple calculator class."""

  def double(self, number):
    return 2 * number

if __name__ == '__main__':

Then, from the command line, you can run:

python calculator.py double 10  # 20
python calculator.py double --number=15  # 30

I had a requirement of using various python utilities (range, string, etc.) on the command line and had written the tool pyfunc specifically for that. You can use it to enrich you command line usage experience:

 $ pyfunc -m range -a 1 7 2

 $ pyfunc -m string.upper -a test

 $ pyfunc -m string.replace -a 'analyze what' 'what' 'this'
 analyze this

It is always an option to enter python on the command line with the command python

then import your file so import example_file

then run the command with example_file.hello()

This avoids the weird .pyc copy function that crops up every time you run python -c etc.

Maybe not as convenient as a single-command, but a good quick fix to text a file from the command line, and allows you to use python to call and execute your file.


Something like this: call_from_terminal.py

# call_from_terminal.py
# Ex to run from terminal
# ip='"hi"'
# python -c "import call_from_terminal as cft; cft.test_term_fun(${ip})"
# or
# fun_name='call_from_terminal'
# python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
def test_term_fun(ip):
    print ip

This works in bash.

$ ip='"hi"' ; fun_name='call_from_terminal' 

Below is the Odd_Even_function.py file that has the definition of the function.

def OE(n):
    for a in range(n):
        if a % 2 == 0:
            print(a, "ODD")

Now to call the same from Command prompt below are the options worked for me.

Options 1 Full path of the exe\python.exe -c "import Odd_Even_function; Odd_Even_function.OE(100)"

Option 2 Full path of the exe\python.exe -c "from Odd_Even_function import OE; OE(100)"



This function cannot be run from the command line as it returns a value which will go unhanded. You can remove the return and use print instead


Use the python-c tool (pip install python-c) and then simply write:

$ python-c foo 'hello()'

or in case you have no function name clashes in your python files:

$ python-c 'hello()'
  • Doesn't work on Python 3 – OrangeDog Mar 12 '18 at 16:07
  • Thank you for bringing this up. I will add support for python 3 – weakmoons Mar 12 '18 at 19:57

First you have to call the function as they told you or the founction will display nothing in the output, after that save the file and copy the path of the file by right click to the folder of the file and click on"copy file" then go to terminal and write: - cd "the path of the file" - python "name of the file for example (main.py)" after that it will display the output of your code.

Your Answer

