How to make sure python script uses virtual environment?

前端 未结 2 798
执念已碎
执念已碎 2021-01-23 01:20

I created virtual environment and activate it. installed packages but unable to import them from virtual environment.

pip freeze:

But

相关标签:
2条回答
  • 2021-01-23 01:24

    In many cases it's not necessary to activate a virtual environment. Typically you could do something like the following from anywhere without activating the virtual environment:

    • C:\path\to\venv\Scripts\python.exe -m pip somecommand
    • C:\path\to\venv\Scripts\python.exe different\path\to\script.py
    • etc.

    Additionally you could specify the absolute path to the python.exe as a she-bang at the top of your Python script, and execute the script directly (for example with a double-click) without calling Python explicitly.

    #!/path/to/venv/bin/python3
    
    print("Hello world")
    

    References:

    • https://docs.python.org/3/using/windows.html#shebang-lines
    • https://docs.python.org/3/library/venv.html#creating-virtual-environments
    0 讨论(0)
  • 2021-01-23 01:34

    You should invoke the python that is installed within your environment. That is

    source myenv/bin/activate
    python path/to/script.py
    

    In Unix, you would add the following #!/usr/bin/env python at the top of your script and this would allow you to run it without specifying the python binary.

    source myenv/bin/activate
    path/to/script.py
    

    Possibly that works in Windows in the same way or differently.

    0 讨论(0)
提交回复
热议问题