2024-04-26 11:00:05 +01:00
|
|
|
---
|
|
|
|
id: atzw
|
|
|
|
tags: []
|
2024-04-28 11:50:05 +01:00
|
|
|
created: Friday, April 26, 2024
|
2024-04-26 11:00:05 +01:00
|
|
|
---
|
2024-04-28 11:50:05 +01:00
|
|
|
|
2024-10-19 10:00:02 +01:00
|
|
|
# Single file Python scripts
|
2024-04-26 11:00:05 +01:00
|
|
|
|
2024-04-28 11:50:05 +01:00
|
|
|
## Basic architecture
|
|
|
|
|
|
|
|
```py
|
|
|
|
#! /usr/local/bin/python3
|
|
|
|
|
|
|
|
import sys
|
2024-04-26 11:00:05 +01:00
|
|
|
|
2024-04-28 11:50:05 +01:00
|
|
|
if __name__ == "__main__":
|
|
|
|
all_args = sys.argv
|
|
|
|
specific_arg = sys.argv[0]
|
|
|
|
# Main functionality...
|
|
|
|
```
|
2024-04-26 11:00:05 +01:00
|
|
|
|
2024-04-28 11:50:05 +01:00
|
|
|
When you run a script (module) Python assigns the string `__main__` to the
|
|
|
|
`__name__` attribute to the script that is being executed.
|
2024-04-26 11:00:05 +01:00
|
|
|
|
2024-04-28 11:50:05 +01:00
|
|
|
If you run the script as an import into another script, the `__name__` attribute
|
|
|
|
of the imported module is set to the module name, not `__main__`.
|
2024-04-28 12:00:05 +01:00
|
|
|
|
|
|
|
Everything can go under the `__main__` conditional, or, for better readability,
|
|
|
|
you can define a `main` function that is then invoked, e.g:
|
|
|
|
|
|
|
|
```py
|
|
|
|
|
|
|
|
def main():
|
|
|
|
# Do some stuff
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
## Related notes
|
|
|
|
|
|
|
|

|