How to Run a Python File in The Terminal?
In this article, I share with you the simple way to run Python scripts in the terminal, as well as the more complex method.
The easiest way to run a Python file in the terminal is to navigate to the file's folder and, in there, run the following command:
python name_of_script.py
This solution makes sense. If that's what you need, great!
What if you get an error saying some imports are failing? That means you're not running a standalone Python file and must run it in module form.
How to Run a Python Module in The Terminal?
When you run a Python file as a module, you essentially treat the entire file as the code that needs to run, and if you have a "main" section, that would be the entry point code that runs while everything else is loaded to the memory.
So how do you do that? First off, you need to consider the context. You can't run a file as a module from the same folder level if you have another module in sub-folders on the same level. Let's consider this structure:
- src
- app
- app.py
- handlers
- handler.py
- services
- manager.py
In this case, if you want the code in app.py to be able to run code from manager.py or handler.py, you'll have to run it as a module from the src folder like so:
python -m app.app
Why is src not part of it? Because src is the root. You run the code from within that folder, but it's not part of the code's structure for execution purposes. Nothing in your code knows src
exists, but your code does know that app
exists and might have multiple Python files in that folder ready to run.
The Importance of __init__.py Files
The init files allow the Python interpreter to understand the structure of your app. While their absence may not cause problems in some cases, it's crucial to include them when running Python code as a module. The absence of these files will also cause problems with type checks, which we can discuss in a separate article.
These files should also be empty. They can include some imports, but that's advanced and could cause problems if you don't know what you're doing. Just create the files in your project folders and leave them empty. The interpreter will do the rest.
Here's the corrected structure with the init files:
- src
- app
- __init__.py
- app.py
- handlers
- __init__.py
- handler.py
- services
- __init__.py
- manager.py
The src folder should NOT include an init file. That will cause problems with your imports.
If what you're building a python package, the init files are becoming even more important to help with hints when someone uses the package.
Thanks For Reading!
If you have any questions or want me to explain something further, please do feel free to let me know by commenting below or replying to this post if you got it as an email 😄
I'll see you in the next one!