|
| 1 | +When you write a program for yourself (or download a Python program from the internet), you will |
| 2 | +probably want to run it sooner or later. |
| 3 | + |
| 4 | +This is quite straightforward. You can simply follow these steps: |
| 5 | +* Open the terminal program you use (on Windows this might be called "Power Shell" or "CMD"), |
| 6 | +* Navigate to the folder where the program is stored, |
| 7 | +* Run the program by typing `python my_cool_program.py` (also known as running a "script"). |
| 8 | + |
| 9 | +There is an important problem when building programs that you should be aware of: any top-level code |
| 10 | +always runs when you run the script **BUT ALSO** at _import_ time. That's right! You can `import` |
| 11 | +your program too. |
| 12 | + |
| 13 | +This is a problem because, you probably don't expect to be running Python code just because you |
| 14 | +`import`ed something. To avoid this you can use a trick to check if your code is being run as a script |
| 15 | +or if it's being imported. |
| 16 | + |
| 17 | +There is a special variable that Python gives you called `__name__` which is the name of the current |
| 18 | +module. Try this in your own programming environment if you like: create 2 files. |
| 19 | + |
| 20 | +A file "a.py" should contain: |
| 21 | +```python |
| 22 | +print("__name__ is: ", __name__) |
| 23 | +``` |
| 24 | + |
| 25 | +A file "b.py" should contain: |
| 26 | +```python |
| 27 | +import a |
| 28 | +print("I'm in b") |
| 29 | +``` |
| 30 | + |
| 31 | +Now run `python a.py` (Use a.py as a script, not importing it). This should be printed to the console: |
| 32 | +``` |
| 33 | +__name__ is: __main__ |
| 34 | +``` |
| 35 | + |
| 36 | +And if you run `python b.py` (Import a.py). This should print: |
| 37 | +``` |
| 38 | +__name__ is: a |
| 39 | +I'm in b |
| 40 | +``` |
| 41 | + |
| 42 | +Notice that the special variable `__name__` contains `"__main__"` when you run the file as a script. |
| 43 | +So when you define code to run when using your program as a script you should use this construction: |
| 44 | +```python |
| 45 | +if __name__ == "__main__": |
| 46 | + # code to run when using my program as a script. |
| 47 | + |
| 48 | +``` |
| 49 | + |
0 commit comments