1

Using Windows, I cannot get my python script to use my virtual environment when executing in a text editor (Atom).

I know how to use the command line to get my script to use my virtual environment (by activating my virtual environment and running the script) but I want to be able to work in the text editor.

I tried to include the shebang #!/usr/bin/env python to indicate to my script to use the virtual environment (as suggested here), but Windows might not actually support shebangs (from here and here). I attempted to directly state the path of my virtual environment but it wasn't clear how to do that (I tried variations of #!"C:\Users\...\my_project\venv\Scripts\python.exe")

Note that my file structure is a folder (my_project) containing two folders, venv (my virtual environment) and my_code (which contains my_script.py).

The following script prints paths from my virtual environment when executed from the command line but paths from my system when executed from the text editor. Additionally, I have installed sklearn globally but not in my virtual environment, and sklearn fails to import when executed from the command line (as desired) but imports when executed from the text editor (not desired).

#!/usr/bin/env python

import sys
print(sys.path)

from sklearn.cluster import KMeans

How can I get my script to recognize the virtual environment I want to use?

b.d
  • 88
  • 7

1 Answers1

0

You need to make a virtual environment, and then activate it in order for the script to use the virtual environment. To do it on atom, follow this guide

Following the quote below should work perfectly from command line. (Once activated, cd /path/to/script and then python myscript.py)

Quote from here

To create a virtual environment, decide upon a directory where you want to place it, and run the venv module as a script with the directory path:

python3 -m venv tutorial-env

Once you’ve created a virtual environment, you may activate it.

On Windows, run:

tutorial-env\Scripts\activate.bat

Community
  • 1
  • 1
Column01
  • 152
  • 1
  • 13
  • Thanks for the feedback. I already had the command line route working, but don't know how to get the file to just run on its own when executed with a text editor. I took a look at the guide you linked but I don't see how I can use it to make my script recognize the virtual environment in its directory. – b.d May 15 '19 at 19:38
  • Well it is a n addon for atom if I understand it. You install it and then you can choose the environment for the script to use. – Column01 May 20 '19 at 15:08