Source: Python Scripting — Connected Objects
Passing Script Arguments
sys.argv
import sys
# python myscript.py first 2 True
# sys.argv = ['myscript.py', 'first', '2', 'True']- Always a list of strings
- First element is always the script name
argparse (preferred)
import argparse
parser = argparse.ArgumentParser()
# Positional (mandatory, order matters)
parser.add_argument("word", type=str)
parser.add_argument("number", type=int)
parser.add_argument("toggle", type=bool)
args = parser.parse_args()
print(args.word, args.number, args.toggle)Run: python myscript.py first 2 True
# Optional arguments (use -- prefix, order doesn't matter)
parser.add_argument("--word", type=str)
parser.add_argument("--number", type=int)Run: python myscript.py --word first --number 2
Missing optional args → value is None.
argparse auto-generates --help / error messages.
__name__ and Top-Level Environment
When Python runs a file, __name__ is set to:
"__main__"if the file is run directly (python my_script.py)- The module name (filename without .py) if the file is imported by another script
# When imported: __name__ == "your_script"
# When run directly: __name__ == "__main__"
print(__name__)The if __name__ == "__main__": guard
def main():
# your real logic here
pass
if __name__ == "__main__":
main() # only executes when run as a script, not when importedWhy use it: Prevents top-level code from running when your file is imported as a module by another script.
See Also
- Python Essentials topic