8

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.

silkfire
  • 24,585
  • 15
  • 82
  • 105
blountdj
  • 599
  • 1
  • 11
  • 23

3 Answers3

9

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

FlyingTeller
  • 17,638
  • 3
  • 38
  • 53
  • @blountdj, did you manage to set it up using a .bat file. I don't think pycharm produces it for its environments. How do I get it? – Kvothe Feb 08 '21 at 15:13
  • @Kvothe it is in `\venv\Scripts\activate.bat`. That is the default location where pycharm creates a venv – FlyingTeller Feb 08 '21 at 15:25
  • Thanks for the reply, but my environment directory does not contain `Scripts`. It contains directories called `bin`, `include`, `lib`, `lib64` (link only) and `share`. `bin` does contain something called `activate` but it has no '.bat' extension. – Kvothe Feb 08 '21 at 15:30
  • What is your OS? And which virtualenv tool are you using? – FlyingTeller Feb 08 '21 at 15:35
  • Ubuntu 20.04, created the environment using Pycharm. – Kvothe Feb 08 '21 at 15:35
  • A `.bat` file is a DOS script that can be run using `cmd` on windows. Of course it will not be there on ubuntu. `source bin/activate` will activate your environment – FlyingTeller Feb 08 '21 at 15:37
  • That makes sense. Thank you! – Kvothe Feb 08 '21 at 15:40
2

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.

TaekYoung
  • 45
  • 7
0

Or
source <path to your environment>/bin/activate
on linux