使用venv时,环境$ PATH不同 [英] Environment $PATH different when using venv

查看:209
本文介绍了使用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显示正确的PATH.如果我停用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或将.bash_profile中的PATH变量定义移至会话初始化脚本(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不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆