Executable Python Scripts
Some python files execute logic. You can write the logic straight in the file, but now you can’t import the file without executing the logic.
Take the following example that takes two values and multiplies them:
#!/user/bin/env python3
import sys
print(int(sys.argv[1]) * int(sys.argv[2]))
If you tun the script with python3 test.py 2 4 you will see “8” returned. But if you try and import the module the following happens:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/tmp/foo.py", line 5, in <module>
print(int(sys.argv[1]) * int(sys.argv[2]))
IndexError: list index out of range
Rewritten as follows the file is importable without side effects.
#!/user/bin/env python3
import sys
def main(argv):
print(int(argv[1]) * int(argv[2]))
if __name__ == '__main__':
main(sys.argv)
All logic is now in a method. The variable __name__
refers to the name of
the module, which when run as a script will be set to '__main__'
. The file
now only executes when run, and can be safely imported.