Contents | Previous (3.4 Modules) | Next (3.6 Design Discussion)
This section introduces the concept of a main program or main module.
In many programming languages, there is a concept of a main function or method.
// c / c++intmain(intargc, char*argv[]) {
...
}// javaclassmyprog {
publicstaticvoidmain(Stringargs[]) {
...
}
}This is the first function that executes when an application is launched.
Python has no main function or method. Instead, there is a main module. The main module is the source file that runs first.
bash % python3 prog.py
...Whatever file you give to the interpreter at startup becomes main. It doesn't matter the name.
It is standard practice for modules that run as a main script to use this convention:
# prog.py
...
if__name__=='__main__':
# Running as the main program ...statements
...Statements inclosed inside the if statement become the main program.
Any Python file can either run as main or as a library import:
bash % python3 prog.py # Running as mainimportprog# Running as library importIn both cases, __name__ is the name of the module. However, it will only be set to __main__ if
running as main.
Usually, you don't want statements that are part of the main program
to execute on a library import. So, it's common to have an if-check
in code that might be used either way.
if__name__=='__main__':
# Does not execute if loaded with import ...Here is a common program template for writing a Python program:
# prog.py# Import statements (libraries)importmodules# Functionsdefspam():
...
defblah():
...
# Main functiondefmain():
...
if__name__=='__main__':
main()Python is often used for command-line tools
bash % python3 report.py portfolio.csv prices.csvIt means that the scripts are executed from the shell / terminal. Common use cases are for automation, background tasks, etc.
The command line is a list of text strings.
bash % python3 report.py portfolio.csv prices.csvThis list of text strings is found in sys.argv.
# In the previous bash commandsys.argv# ['report.py, 'portfolio.csv', 'prices.csv']Here is a simple example of processing the arguments:
importsysiflen(sys.argv) !=3:
raiseSystemExit(f'Usage: {sys.argv[0]} ''portfile pricefile')
portfile=sys.argv[1]
pricefile=sys.argv[2]
...Standard Input / Output (or stdio) are files that work the same as normal files.
sys.stdoutsys.stderrsys.stdinBy default, print is directed to sys.stdout. Input is read from
sys.stdin. Tracebacks and errors are directed to sys.stderr.
Be aware that stdio could be connected to terminals, files, pipes, etc.
bash % python3 prog.py > results.txt
# or
bash % cmd1 | python3 prog.py | cmd2Environment variables are set in the shell.
bash % setenv NAME dave
bash % setenv RSH ssh
bash % python3 prog.pyos.environ is a dictionary that contains these values.
importosname=os.environ['NAME'] # 'dave'Changes are reflected in any subprocesses later launched by the program.
Program exit is handled through exceptions.
raiseSystemExitraiseSystemExit(exitcode)
raiseSystemExit('Informative message')An alternative.
importsyssys.exit(exitcode)A non-zero exit code indicates an error.
On Unix, the #! line can launch a script as Python.
Add the following to the first line of your script file.
#!/usr/bin/env python3# prog.py
...It requires the executable permission.
bash % chmod +x prog.py
# Then you can execute
bash % prog.py
... output ...Note: The Python Launcher on Windows also looks for the #! line to indicate language version.
Finally, here is a common code template for Python programs that run as command-line scripts:
#!/usr/bin/env python3# prog.py# Import statements (libraries)importmodules# Functionsdefspam():
...
defblah():
...
# Main functiondefmain(argv):
# Parse command line args, environment, etc.
...
if__name__=='__main__':
importsysmain(sys.argv)In the file report.py add a main() function that accepts a list of
command line options and produces the same output as before. You
should be able to run it interatively like this:
>>>importreport>>>report.main(['report.py', 'Data/portfolio.csv', 'Data/prices.csv'])
NameSharesPriceChange----------------------------------------AA10039.917.71IBM50106.1115.01CAT15078.58-4.86MSFT20030.47-20.76GE9537.38-2.99MSFT5030.47-34.63IBM100106.1135.67>>>Modify the pcost.py file so that it has a similar main() function:
>>>importpcost>>>pcost.main(['pcost.py', 'Data/portfolio.csv'])
Totalcost: 44671.15>>>Modify the report.py and pcost.py programs so that they can
execute as a script on the command line:
bash $ python3 report.py Data/portfolio.csv Data/prices.csv
Name Shares Price Change
---------- ---------- ---------- ----------
AA 100 39.91 7.71
IBM 50 106.11 15.01
CAT 150 78.58 -4.86
MSFT 200 30.47 -20.76
GE 95 37.38 -2.99
MSFT 50 30.47 -34.63
IBM 100 106.11 35.67
bash $ python3 pcost.py Data/portfolio.csv
Total cost: 44671.15Contents | Previous (3.4 Modules) | Next (3.6 Design Discussion)