Hi everybody. I've created a .py file with a simple function in it. Now i want to call that function from linux shell scripting. How should i do that? please help me, thank you.

Recommended Answers

All 20 Replies

Can you post your script? It depends on what you want to do. For example, here is a function which prints hello world

#!/usr/bin/env python
# -*-coding: utf8-*-
# This is file hello.py
# Line 1 above tells the linux shell that this
# program must be executed with python. Replace
# python with python3 if needed.
# Line 2 above tells python that this file is
# encoded in utf8

# our function definition

def thefunc():
    print('hello world')

if __name__ == '__main__':
    # this block contains the code that will be executed
    # when hello.py is executed on the command line
    # It calls our function thefunc()
    thefunc()

Now save this file under the name hello.py, then in a terminal run the 2 commands

chmod +x hello.py
./hello.py

Thank you for your answer.
Here is what i have; a file with name message.py:

def sayhi():
    print('hi everybody!')


if __name__ == "__main__":
    sayhi(int(argv[0]))

Well it's a little hard to explain what i mean....i want to type this for example python message.py sayhi on the shell and run the function.

In fact; i want to create some functions on message.py file and then call each of them separately from the terminal.

Then the script must take an argument which is the function name. The best thing to do is to use the argparse module to parse the command line, something like

#!/usr/bin/env python3
# -*-coding: utf8-*-

def sayhi():
    print('hi everybody!')


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Execute a function')
    parser.add_argument('funcname',
        help='name of function to execute',
        metavar='FUNCNAME',
        choices=['sayhi'])
    args = parser.parse_args()
    function = globals()[args.funcname]
    function()

If you saved your file as hello.py somewhere Python looks for, do this from the shell:

>>> import hello
>>> hello.thefunc()

Or simpler:
>>> execfile("hello.py")

Or simpler:
>>> execfile("hello.py")

You might have to give it the full file path.

python file.py

Thank you Gribouillis, i copied the code you wrote and it worked with python message.py sayhi.

Now for working with more functions what should i do?
Please look at this:

#!/usr/bin/env python3
# -*-coding: utf8-*-

def sayhi():
    print('hi everybody!')

def goodbye():
    print('see you soon!')

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Execute a function')
    parser.add_argument('funcname',
    help='name of function to execute',
    metavar='FUNCNAME',
    choices=['sayhi'])
args = parser.parse_args()
function = globals()[args.funcname]
function()


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Execute a function')
    parser.add_argument('funcname',
    help='name of function to execute',
    metavar='FUNCNAME',
    choices=['goodbye'])
args = parser.parse_args()
function = globals()[args.funcname]
function()

Here i've added an other function goodbye.
When i type python message.py sayhi and python message.py goodbye, just one of them will work. How can i call noth of them separately? How should i change the code above?
_______________
Thanks everybody for all answers :)

#!/usr/bin/env python3
# -*-coding: utf8-*-
def sayhi():
    print('hi everybody!')
def goodbye():
    print('see you soon!')
if __name__ == "__main__":
    sayhi()
    goodbye()

Slavi, i copied your code, but when i type python message.py sayhi bout print messages will be displayed! 'hi everybody!' and 'see you soon' bout will be displayed to gather at the same time.

oh did u mean to be able to call them separately

Yes. I want when i type python message.py sayhi, the function sayhi run and when type python message.py goodbye, the function goodbye run separately.

In fact; i want to have some different functions in message.py file and call them separately everytime by typing python message.py (the name of the function).

I thought you want to do it from the Python shell?

Yes! From Linux's terminal in python language.
Sorry maybe i couldn't explain good, well my English is not very good. So....let me make it clear.
I want to type this command python message.py sayhi for example, from the Linux terminal.

On my Raspberry Pi computer I came up with this:

#!/usr/bin/python2
# -*- coding: utf-8 -*-
"""
Save this file as hello_arg2.py in folder
/home/pi/rpi_python

Note: line 1 has been changed to fit Debian/Rasbian Linux

Results in the Linux Python2 shell -->
>>> import sys
>>> sys.argv = ["hello_arg2.py", "sayhi"]
>>> execfile("/home/pi/rpi_python/hello_arg2.py")
Hello to you!
>>> sys.argv = ["hello_arg2.py", "saybye"]
>>> execfile("/home/pi/rpi_python/hello_arg2.py")
Hasta la vista!

note Python3 has removed execfile(), now use
>>> exec(open("/home/pi/rpi_python/hello_arg2.py").read())

"""

def sayhi():
    print("Hello to you!")

def saybye():
    print("Hasta la vista!")


if __name__ == '__main__':
    import sys
    # there is a commandline
    if len(sys.argv) > 1:
        # sys.argv[0] is the program filename
        if sys.argv[1] == "sayhi":
            sayhi()
        elif sys.argv[1] == "saybye":
            saybye()
    else:
        print("usage hello_arg2 sayhi  or  hello_arg2 saybye")
    Using the LXTerminal -->
    cd rpi_python
    python hello_arg2.py sayhi
    or -->
    python hello_arg2.py saybye

Use argparse ! It is by far the best way to do this

#!/usr/bin/env python3
# -*-coding: utf8-*-

def sayhi():
    print('hi everybody!')

def goodbye():
    print('see you soon!')

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Execute a function')
    parser.add_argument('funcname',
        help='name of function to execute',
        metavar='FUNCNAME',
        choices=['goodbye', 'sayhi']) # <-- LOOK HERE
    args = parser.parse_args()
    function = globals()[args.funcname]
    function()

Yesssssssssss!! It works Gribouillis thank you so much :)
I've created some other functions and all of them works separately, nice!
______________
Thanks everybody for all answers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.