Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Python File from Command Line with Libraries in venv

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.

like image 220
blountdj Avatar asked Feb 12 '18 08:02

blountdj


People also ask

How do I run a Python file in VENV?

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 .

How do I run a Python virtual environment in CMD?

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.


2 Answers

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

like image 143
FlyingTeller Avatar answered Oct 19 '22 23:10

FlyingTeller


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.

like image 30
TaekYoung Avatar answered Oct 19 '22 22:10

TaekYoung