I'm using Python 3.6 in Windows and using PyCharm. I have a .py file that is using packages installed on a venv which is in a different folder to the .py file.
I'm trying to run this .py from command line and when I do it gives me a ModuleNotFoundError: No module named '<module>'
. The file works fine from PyCharm just not from the command line because the packages are in the venv.
How can I get the file to run without errors from command line and keep the packages in the venv?
Many thanks.
To use the virtual environment you created to run Python scripts, simply invoke Python from the command line in the context where you activated it. For instance, to run a script, just run python myscript.py .
Open the Windows Command Prompt enter into your Desktop folder with the command cd desktop . You can find your device's command line interface (CLI) by searching in your applications.> Type py -m venv env to create a virtual environment named env . When the environment is created, the prompt will reappear.
You need to activate the virtual environment by callling the activation script:
<path to your environment>\Scripts\activate.bat
as indicated here. Then you will automatically use all the packages installed in this environment when calling your script. Your pycharm is probably set up to automatically use your virtual evnironment
I Think the easiest way to do that is using shebang, and it works both linux and windows.
For windows you just have to add #!.\venv\Scripts\python.exe
at the very first line at your .py script file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With