How to Run a Python File in The Terminal?
Quick and easy tutorial on how to run python files in the terminal.
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 file_name.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 (in the root of your folder)
- app
- app.py
- services
- manager.py
- handlers
- handler.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
# -m is the module parameter.
# app.app refers to the app folder and the app module inside it.
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 (in the root of your folder)
- app
- app.py
- __init__.py
- services
- __init__.py
- manager.py
- handlers
- __init__.py
- handler.py
The src folder should NOT include an init file. That will cause problems with your imports.
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!