February 2022
Intermediate to advanced
274 pages
6h 28m
English
We can change our script code a tiny bit to make it importable and allow tests and code to be in different directories. We’ll start by making sure all of the logic in the script is inside a function. Let’s move the workload of hello.py into a main() function:
| | def main(): |
| | print("Hello, World!") |
| | |
| | |
| | if __name__ == "__main__": |
| | main() |
We call main() inside a if __name__ == ’__main__’ block. The main() code will be called when we call the script with python hello.py:
| | $ cd /path/to/code/ch12/script_importable |
| | $ python hello.py |
| | Hello, World! |
The main() code won’t be called with just an import. We have to call main() explicitly:
| | $ python |
| |
Read now
Unlock full access