Reputation: 997
I have been around many similar questions and articles and tried many different ways but still fail at finding where the problem is.
I created a new project in pycharm and set it as root. Then created a script at the root level that holds some variables i want to import in the scripts of sub-directories.
Here's the result of the unix tree
command:
root_project
├── subfolder
│ └── sub_script.py
└── variables_i_need.py
the content of variables_i_need.py is simply name = "john"
the content of sub_script.py is
from variables_i_need import name
if __name__ == "__main__":
print(name)
Now, when i run the sub_script.py using the play button of the sub_script, it works and the run console prints:
/usr/bin/python3.8 /home/root_project/subfolder/sub_script.py
john
Process finished with exit code 0
But when I try to run it from the command line it breaks:
python3 sub_script.py
~/Desktop/root_project/subfolder » python3 sub_script.py gabri@gabriele-computer
Traceback (most recent call last):
File "sub_script.py", line 1, in <module>
from variables_i_need import name
ModuleNotFoundError: No module named 'variables_i_need'
Upvotes: 0
Views: 2124
Reputation: 5580
If you look into PyCharm configuration, there are two options:
They are flagged by default.
In your case, the first one allows you to run the script correctly because it adds root_project path in the PYTHONPATH environment variable.
So, if you want to run the script also in command line you should set the same variable.
You can proceed like this:
Open command line
If you are on Linux you can use
export PYTHONPATH=<absolute_path_of_root_project>
If you are on Windows you can use
SET PYTHONPATH=<absolute_path_of_root_project>
Run script
~/Desktop/root_project/subfolder » python3 sub_script.py
Please remember that the export/set command is not permanent, it is valid for the current command line session.
Upvotes: 2