how to execute .py script from bash shell

12,762

Solution 1

Suppose if your script file name is mycode.py then you can use python -i mycode.py:

$ python -i mycode.py
>>> area(10, 5)   

-i When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. refrence

Solution 2

The reason nothing happens is because you haven't called your method in your script, so the file simply defines the method and then quits. This is a quick fix:

def area(base,height):
    ''' (number, number) - number
    Return area of a triangle with dimensions base * height

    >>>>area(10,5)
    25.0
    '''
    return base*height/2

print area(10,5) # calling the method

The proper way to fix this is to add this check:

if __name__ == '__main__':
    print area(10,5)

When Python scripts are run from the command line, the special variable __name__ is set to the string '__main__' (see this answer for more). That if statement essentially says, "If I am run from the command line, execute the method area with the arguments 10 and 5 and print the results."

Finally, to make sure your script can be run from the prompt like this ./myscript.py, you need to tell your shell how to execute it. This is done by adding a shebang line to the top of your file.

Combining all that, your file looks like:

#!/usr/bin/python

def area(base,height):
        ''' (number, number) - number
        Return area of a triangle with dimensions base * height

        >>>>area(10,5)
        25.0
        '''
        return base*height/2

if __name__ == '__main__':
    print area(10,5)
Share:
12,762
aaron
Author by

aaron

Updated on June 14, 2022

Comments

  • aaron
    aaron almost 2 years

    I open a terminal and cd into my documents where I have my .py file called trianglearea.py which is a very basic program that I am trying to execute. I type /Documents$ python trianglearea.py into the shell and nothing happens; bash prompts me for another command as if what I just prompted doesn't exist. I try ./trianglearea.py but I get a syntax error because I have not entered interactive python and bash doesn't understand my python script. If I go to the file gui style and double click and say run in terminal a window flashes and disappears but that is not what I want. I want to have my little program run in interactive python so I can enter stuff and actually use my function. This is all I have in the.py file

    def area(base,height):
        ''' (number, number) - number
        Return area of a triangle with dimensions base * height
    
        >>>>area(10,5)
        25.0
        '''
        return base*height/2
    

    I know this shouldn't be that hard but it has stumped me.