使用 venv 时环境 $PATH 不同

Environment $PATH different when using venv(使用 venv 时环境 $PATH 不同)

本文介绍了使用 venv 时环境 $PATH 不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Mac(OSX 小牛)上使用 PyCharm 来运行如下所示的简单脚本.它所做的只是打印 PATH 变量.我在项目目录中有一个 virtualenv.我在 PyCharm 中添加了一个运行配置,并用不同的 Python 进行了尝试:

I'm using PyCharm on a mac (OSX mavericks) to run a simple script shown below. All it does is print the PATH variable. I have a virtualenv in the project directory. I added a Run Configuration in PyCharm and tried it with different Pythons:

# file mytest.py
import os
print "PATH: ", os.environ['PATH']

当我使用系统默认 python (/usr/bin/python) 运行时,它会打印正确的 PATH 值(即我在 .bash_profile 文件中配置的 PATH),它有点长并且包含许多目录.

When I run with the system default python (/usr/bin/python) it prints the correct value for PATH (i.e. the PATH as I have configured in my .bash_profile file,) which is kind of long and contains many directories.

但是当我选择 venv 的 Python 时,路径减少到只有:/usr/bin:/bin:/usr/sbin:/sbin:/Users/myname/projects/myproj/venv/bin

But when I choose the venv's Python, the path is reduced to only: /usr/bin:/bin:/usr/sbin:/sbin:/Users/myname/projects/myproj/venv/bin

如果我从终端窗口运行脚本,则不会发生这种情况.在这种情况下,它显示了系统 python 和 venv python 的正确路径.如果我停用 venv 并运行 venv/bin/python mytest.py,它也不会发生.

This doesn't happen if I run the script from a terminal window. In this case it shows the correct PATH for both the system's python and the venv python. It also doesn't happen if I deactivate the venv and run venv/bin/python mytest.py.

有人知道在从 PyCharm 运行并使用 venv 时如何设置正确的 PATH 值吗?

Anyone knows how to make the correct PATH value be set when running from PyCharm and using venv?

推荐答案

你应该知道所有的环境变量都是继承的.当您在 .bash_profile 中定义环境变量时,它在您的终端(bash)中可用,并且在将从终端启动的所有进程中(这些进程将是 bash 进程的子进程).这就是从终端运行脚本时获得预期值的原因.

you should probably know that all environment variables are inherited. When you define environment variable in your .bash_profile it becomes available in your terminal (bash), and in all processes that will be started from terminal (These processes will be children for the bash process). That's why you are getting expected values when running your script from within the terminal.

您不是从终端启动 PyCharm,因此它不会继承 PATH.Python 或 venv 也是如此(它们是从 PyCharm 启动的).

You start PyCharm not from a terminal, so it doesn't inherit PATH. And so do Python or venv (they launched from PyCharm).

要解决您的问题,您有 3 个选项:只需从终端启动 PyCharm 或将 PATH 变量定义从 .bash_profile 移动到会话初始化脚本(PATH 将在系统范围内定义)或在 PyCharm 的运行配置中复制您的 PATH(它有那里有这样的选择)

To solve your issue you have 3 options here: just start PyCharm from terminal or move PATH variable definition from .bash_profile to session init scripts (PATH will be defined system-wide) or Duplicate your PATH in PyCharm's run configuration (it has such option over there)

祝你好运!

这篇关于使用 venv 时环境 $PATH 不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 venv 时环境 $PATH 不同