标签归档:virtualenv

使用virtualenvwrapper重命名环境

问题:使用virtualenvwrapper重命名环境

我有一个名为的环境doors,我想将其重命名djangovirtualenvwrapper

我注意到,如果仅将文件夹重命名~/.virtualenvs/doorsdjango,我现在可以呼叫workon django,但是环境仍然提示(doors)hobbes3@hobbes3

I have an environment called doors and I would like to rename it to django for the virtualenvwrapper.

I’ve noticed that if I just rename the folder ~/.virtualenvs/doors to django, I can now call workon django, but the environment still says (doors)hobbes3@hobbes3.


回答 0

您可以使用:

cpvirtualenv oldenv newenv
rmvirtualenv oldenv

因此,在您的情况下:

cpvirtualenv doors django
rmvirtualenv doors

You can use:

cpvirtualenv oldenv newenv
rmvirtualenv oldenv

So in your case:

cpvirtualenv doors django
rmvirtualenv doors

回答 1

如果您这样做:

$ ack-grep -ai doors ~/.virtualenvs/django/bin

您会注意到,该文件将doors作为位置而不是django,您将使用新位置更改每个文件。

解决方案:重命名文件夹后,执行以下命令。

$ sed -i "s/doors/django/g" ~/.virtualenvs/django/bin/*

现在,如果您这样做:

$ workon django
(django)hobbes3@hobbes3

if you do:

$ ack-grep -ai doors ~/.virtualenvs/django/bin

you’ll notice that will have doors as location and not django, you’ll to change each file with the new location.

solution: after renamed the folder execute the command below.

$ sed -i "s/doors/django/g" ~/.virtualenvs/django/bin/*

now if you do:

$ workon django
(django)hobbes3@hobbes3

如何在virtualenv中向PYTHONPATH添加路径

问题:如何在virtualenv中向PYTHONPATH添加路径

我正在尝试向PYTHONPATH环境变量添加路径,该路径仅在特定的virtualenv环境中可见。

SET PYTHONPATH=...在virtualenv命令提示符下进行了尝试,但这为整个环境设置了变量。

我该如何实现?

I am trying to add a path to the PYTHONPATH environment variable, that would be only visible from a particular virtualenv environment.

I tried SET PYTHONPATH=... under a virtualenv command prompt, but that sets the variable for the whole environment.

How do I achieve that?


回答 0

通常,您可以通过使用.pthfiles来避免对PYTHONPATH做任何事情。只需在您的virtualenv的site-packages文件夹中放入一个扩展名为.pth的文件(任何基本名称均有效),例如lib\python2.7\site-packages,将包含软件包的目录的绝对路径作为其唯一内容。

You can usually avoid having to do anything with PYTHONPATH by using .pth files. Just put a file with a .pth extension (any basename works) in your virtualenv’s site-packages folder, e.g. lib\python2.7\site-packages, with the absolute path to the directory containing your package as its only contents.


回答 1

如果使用virtualenv,则可能还应该使用virtualenvwrapper,在这种情况下,可以使用add2virtualenv命令将路径添加到当前virtualenv的Python路径:

add2virtualenv directory1 directory2 …

If you’re using virtualenv, you should probably also be using virtualenvwrapper, in which case you can use the add2virtualenv command to add paths to the Python path for the current virtualenv:

add2virtualenv directory1 directory2 …


回答 2

您也可以尝试将符号链接放入您的virtualenv之一。

例如。1)激活您的virtualenv 2)运行python 3)导入sys并检查sys.path 4)您将在那里找到python搜索路径。选择其中一个(例如站点软件包)5)转到其中,并创建指向您软件包的符号链接,例如:ln -s您要导入的软件包名称路径

这样,即使不激活virtualenv,您也应该能够导入它。只需尝试:进入您的virtualenv-folder / bin / python路径并导入您的包。

You can also try to put symlink to one of your virtualenv.

eg. 1) activate your virtualenv 2) run python 3) import sys and check sys.path 4) you will find python search path there. Choose one of those (eg. site-packages) 5) go there and create symlink to your package like: ln -s path-to-your-package name-with-which-you’ll-be-importing

That way you should be able to import it even without activating your virtualenv. Simply try: path-to-your-virtualenv-folder/bin/python and import your package.


回答 3

如果您使用virtualenvwrapper,

$ cd to the parent folder
$ add2virtualenv  folder_to_add

控制台将显示

Warning: Converting "folder_to_add" to "/absoutle/path/to/folder_to_add"

就是这样,您应该很好

If you are using virtualenvwrapper,

$ cd to the parent folder
$ add2virtualenv  folder_to_add

console will display

Warning: Converting "folder_to_add" to "/absoutle/path/to/folder_to_add"

That’s it, and you should be good to go


回答 4

import sys
import os

print(str(sys.path))

dir_path = os.path.dirname(os.path.realpath(__file__))
print("current working dir: %s" % dir_path)

sys.path.insert(0, dir_path)

我强烈建议您使用virtualenv和virtualenvwrapper以避免路径混乱。

import sys
import os

print(str(sys.path))

dir_path = os.path.dirname(os.path.realpath(__file__))
print("current working dir: %s" % dir_path)

sys.path.insert(0, dir_path)

I strongly suggest you use virtualenv and virtualenvwrapper to avoid cluttering the path.


如何在Bash脚本中激活virtualenv源

问题:如何在Bash脚本中激活virtualenv源

如何创建Bash脚本来激活Python virtualenv?

我有一个类似的目录结构:

.env
    bin
        activate
        ...other virtualenv files...
src
    shell.sh
    ...my code...

我可以通过以下方式激活我的virtualenv:

user@localhost:src$ . ../.env/bin/activate
(.env)user@localhost:src$

但是,从Bash脚本执行相同操作将不会执行以下操作:

user@localhost:src$ cat shell.sh
#!/bin/bash
. ../.env/bin/activate
user@localhost:src$ ./shell.sh
user@localhost:src$ 

我究竟做错了什么?

How do you create a Bash script to activate a Python virtualenv?

I have a directory structure like:

.env
    bin
        activate
        ...other virtualenv files...
src
    shell.sh
    ...my code...

I can activate my virtualenv by:

user@localhost:src$ . ../.env/bin/activate
(.env)user@localhost:src$

However, doing the same from a Bash script does nothing:

user@localhost:src$ cat shell.sh
#!/bin/bash
. ../.env/bin/activate
user@localhost:src$ ./shell.sh
user@localhost:src$ 

What am I doing wrong?


回答 0

当您获取资源时,您会将激活脚本加载到活动的shell中。

当您在脚本中执行此操作时,将其加载到该外壳中,该外壳将在脚本完成后退出,并且返回到未激活的原始外壳。

最好的选择是在函数中执行此操作

activate () {
  . ../.env/bin/activate
}

或别名

alias activate=". ../.env/bin/activate"

希望这可以帮助。

When you source, you’re loading the activate script into your active shell.

When you do it in a script, you load it into that shell which exits when your script finishes and you’re back to your original, unactivated shell.

Your best option would be to do it in a function

activate () {
  . ../.env/bin/activate
}

or an alias

alias activate=". ../.env/bin/activate"

Hope this helps.


回答 1

您应该使用source调用bash脚本。

这是一个例子:

#!/bin/bash
# Let's call this script venv.sh
source "<absolute_path_recommended_here>/.env/bin/activate"

在您的shell上这样称呼它:

> source venv.sh

或按照@outmind建议:(请注意,这不适用于zsh)

> . venv.sh

到这里,shell指示将出现在您的提示符下。

You should call the bash script using source.

Here is an example:

#!/bin/bash
# Let's call this script venv.sh
source "<absolute_path_recommended_here>/.env/bin/activate"

On your shell just call it like that:

> source venv.sh

Or as @outmind suggested: (Note that this does not work with zsh)

> . venv.sh

There you go, the shell indication will be placed on your prompt.


回答 2

尽管它没有在shell提示符中添加“(.env)”前缀,但我发现此脚本可以按预期工作。

#!/bin/bash
script_dir=`dirname $0`
cd $script_dir
/bin/bash -c ". ../.env/bin/activate; exec /bin/bash -i"

例如

user@localhost:~/src$ which pip
/usr/local/bin/pip
user@localhost:~/src$ which python
/usr/bin/python
user@localhost:~/src$ ./shell
user@localhost:~/src$ which pip
~/.env/bin/pip
user@localhost:~/src$ which python
~/.env/bin/python
user@localhost:~/src$ exit
exit

Although it doesn’t add the “(.env)” prefix to the shell prompt, I found this script works as expected.

#!/bin/bash
script_dir=`dirname $0`
cd $script_dir
/bin/bash -c ". ../.env/bin/activate; exec /bin/bash -i"

e.g.

user@localhost:~/src$ which pip
/usr/local/bin/pip
user@localhost:~/src$ which python
/usr/bin/python
user@localhost:~/src$ ./shell
user@localhost:~/src$ which pip
~/.env/bin/pip
user@localhost:~/src$ which python
~/.env/bin/python
user@localhost:~/src$ exit
exit

回答 3

Sourcing在您当前的shell中运行shell命令。当像上述一样在脚本内部获取源代码时,会影响该脚本的环境,但是当脚本退出时,环境更改将被撤消,因为它们实际上已超出范围。

如果您打算在virtualenv中运行shell命令,则可以在获取激活脚本后在脚本中执行此操作。如果您打算与virtualenv内部的shell进行交互,则可以在脚本内部产生一个继承环境的子shell。

Sourcing runs shell commands in your current shell. When you source inside of a script like you are doing above, you are affecting the environment for that script, but when the script exits, the environment changes are undone, as they’ve effectively gone out of scope.

If your intent is to run shell commands in the virtualenv, you can do that in your script after sourcing the activate script. If your intent is to interact with a shell inside the virtualenv, then you can spawn a sub-shell inside your script which would inherit the environment.


回答 4

这是我经常使用的脚本。运行为$ source script_name

#!/bin/bash -x
PWD=`pwd`
/usr/local/bin/virtualenv --python=python3 venv
echo $PWD
activate () {
    . $PWD/venv/bin/activate
}

activate

Here is the script that I use often. Run it as $ source script_name

#!/bin/bash -x
PWD=`pwd`
/usr/local/bin/virtualenv --python=python3 venv
echo $PWD
activate () {
    . $PWD/venv/bin/activate
}

activate

回答 5

采购bash脚本的目的是什么?

  1. 如果您打算在多个virtualenv之间切换或快速输入一个virtualenv,您是否尝试过virtualenvwrapper?它提供了很多像utils的的workon venvmkvirtualenv venv等等。

  2. 如果您只是在某些virtualenv中运行python脚本,请使用/path/to/venv/bin/python script.py来运行它。

What does sourcing the bash script for?

  1. If you intend to switch between multiple virtualenvs or enter one virtualenv quickly, have you tried virtualenvwrapper? It provides a lot of utils like workon venv, mkvirtualenv venv and so on.

  2. If you just run a python script in certain virtualenv, use /path/to/venv/bin/python script.py to run it.


回答 6

您还可以使用子外壳来更好地包含您的用法-这是一个实际示例:

#!/bin/bash

commandA --args

# Run commandB in a subshell and collect its output in $VAR
# NOTE
#  - PATH is only modified as an example
#  - output beyond a single value may not be captured without quoting
#  - it is important to discard (or separate) virtualenv activation stdout
#    if the stdout of commandB is to be captured
#
VAR=$(
    PATH="/opt/bin/foo:$PATH"
    . /path/to/activate > /dev/null  # activate virtualenv
    commandB  # tool from /opt/bin/ which requires virtualenv
)

# Use the output from commandB later
commandC "$VAR"

此样式在以下情况下特别有用

  • 下的commandAcommandC存在其他版本/opt/bin
  • commandB存在于系统中PATH或非常普遍
  • 这些命令在virtualenv下失败
  • 一个需要各种不同的虚拟环境

You can also do this using a subshell to better contain your usage – here’s a practical example:

#!/bin/bash

commandA --args

# Run commandB in a subshell and collect its output in $VAR
# NOTE
#  - PATH is only modified as an example
#  - output beyond a single value may not be captured without quoting
#  - it is important to discard (or separate) virtualenv activation stdout
#    if the stdout of commandB is to be captured
#
VAR=$(
    PATH="/opt/bin/foo:$PATH"
    . /path/to/activate > /dev/null  # activate virtualenv
    commandB  # tool from /opt/bin/ which requires virtualenv
)

# Use the output from commandB later
commandC "$VAR"

This style is especially helpful when

  • a different version of commandA or commandC exists under /opt/bin
  • commandB exists in the system PATH or is very common
  • these commands fail under the virtualenv
  • one needs a variety of different virtualenvs

回答 7

您应该在一行中使用多个命令。例如:

os.system(". Projects/virenv/bin/activate && python Projects/virenv/django-project/manage.py runserver")

当您在一行中激活虚拟环境时,我认为它会忘记其他命令行,并且可以通过在一行中使用多个命令来防止这种情况。它为我工作:)

You should use multiple commands in one line. for example:

os.system(". Projects/virenv/bin/activate && python Projects/virenv/django-project/manage.py runserver")

when you activate your virtual environment in one line, I think it forgets for other command lines and you can prevent this by using multiple commands in one line. It worked for me :)


回答 8

在学习venv时,我创建了一个脚本来提醒我如何激活它。

#!/bin/sh
# init_venv.sh
if [ -d "./bin" ];then
  echo "[info] Ctrl+d to deactivate"
  bash -c ". bin/activate; exec /usr/bin/env bash --rcfile <(echo 'PS1=\"(venv)\${PS1}\"') -i"
fi

这样做的好处是可以更改提示。

When I was learning venv I created a script to remind me how to activate it.

#!/bin/sh
# init_venv.sh
if [ -d "./bin" ];then
  echo "[info] Ctrl+d to deactivate"
  bash -c ". bin/activate; exec /usr/bin/env bash --rcfile <(echo 'PS1=\"(venv)\${PS1}\"') -i"
fi

This has the advantage that it changes the prompt.


如何在PyCharm终端中激活virtualenv?

问题:如何在PyCharm终端中激活virtualenv?

我已经设置了PyCharm,创建了我的virtualenv(通过virtual env命令,或者直接在PyCharm中),并将那个环境激活为我的解释器。一切正常。

但是,如果我使用“工具,打开终端”打开终端,则提供的shell提示使用虚拟环境。我仍然必须source ~/envs/someenv/bin/activate在该终端内使用才能激活它。

另一种方法是在外壳中激活环境,然后从该环境运行PyCharm。这是“可行的”但很丑陋,这意味着如果我从PyCharm切换环境或项目,我会遇到重大问题:我现在使用的是完全错误的环境。

还有其他更简便的方法来使“工具,打开终端”自动激活虚拟环境吗?

I’ve set up PyCharm, created my virtualenv (either through the virtual env command, or directly in PyCharm) and activated that environment as my Interpreter. Everything is working just fine.

However, if I open a terminal using “Tools, Open Terminal”, the shell prompt supplied is not using the virtual env; I still have to use source ~/envs/someenv/bin/activate within that Terminal to activate it.

Another method is to activate the environment in a shell, and run PyCharm from that environment. This is “workable” but pretty ugly, and means I have major problems if I switch environments or projects from PyCharm: I’m now using the totally-wrong environment.

Is there some other, much-easier way to have “Tools, Open Terminal” automatically activate the virtual environment?


回答 0

编辑:

根据https://www.jetbrains.com/pycharm/whatsnew/#v2016-3-venv-in-terminal的介绍,PyCharm 2016.3(于2016年11月发布)具有开箱即用的virutalenv支持

bash,zsh,fish和Windows cmd支持自动virtualenv。您可以在“设置”(“首选项”)|“自定义”中自定义外壳首选项。工具| 终奌站。


旧方法:

.pycharmrc在主文件夹中创建一个包含以下内容的文件

source ~/.bashrc
source ~/pycharmvenv/bin/activate

使用您的virtualenv路径作为最后一个参数。

然后将Shell Preferences-> Project Settings-> Shell path设置为

/bin/bash --rcfile ~/.pycharmrc

Edit:

According to https://www.jetbrains.com/pycharm/whatsnew/#v2016-3-venv-in-terminal, PyCharm 2016.3 (released Nov 2016) has virutalenv support for terminals out of the box

Auto virtualenv is supported for bash, zsh, fish, and Windows cmd. You can customize your shell preference in Settings (Preferences) | Tools | Terminal.


Old Method:

Create a file .pycharmrc in your home folder with the following contents

source ~/.bashrc
source ~/pycharmvenv/bin/activate

Using your virtualenv path as the last parameter.

Then set the shell Preferences->Project Settings->Shell path to

/bin/bash --rcfile ~/.pycharmrc

回答 1

更新:

设置(首选项)|首选项中的首选项 工具| 终端是全球性的。
如果为每个项目使用venv,请记住使用当前路径变量和默认venv名称:

"cmd.exe" /k ""%CD%\venv\Scripts\activate"" 

对于Windows用户:在虚拟环境中使用PyCharm时,可以使用该/K参数cmd.exe自动设置虚拟环境。

PyCharm 3或4: ,,Settings 和添加。TerminalDefault shell/K <path-to-your-activate.bat>

PyCharm 5: ,SettingsToolsTerminal并添加/K <path-to-your-activate.bat>Shell path

PyCharm 2016.1或2016.2: ,SettingsToolsTerminal并添加""/K <path-to-your-activate.bat>""Shell path,并添加(介意引号)。还要在cmd.exe周围加上引号,导致:

"cmd.exe" /k ""C:\mypath\my-venv\Scripts\activate.bat""

Update:

The preferences in Settings (Preferences) | Tools | Terminal are global.
If you use a venv for each project, remember to use current path variable and a default venv name:

"cmd.exe" /k ""%CD%\venv\Scripts\activate"" 

For Windows users: when using PyCharm with a virtual environment, you can use the /K parameter to cmd.exe to set the virtual environment automatically.

PyCharm 3 or 4: Settings, Terminal, Default shell and add /K <path-to-your-activate.bat>.

PyCharm 5: Settings, Tools, Terminal, and add /K <path-to-your-activate.bat> to Shell path.

PyCharm 2016.1 or 2016.2: Settings, Tools, Terminal, and add ""/K <path-to-your-activate.bat>"" to Shell path and add (mind the quotes). Also add quotes around cmd.exe, resulting in:

"cmd.exe" /k ""C:\mypath\my-venv\Scripts\activate.bat""


回答 2

对于Windows用户,在Windows下使用PyCharm和虚拟环境时,可以使用/ k参数cmd.exe来自动设置虚拟环境。

转到“设置”,“终端”,“默认外壳”并添加/K <path-to-your-activate.bat>

我没有对早期回复发表评论的声誉,因此请发布此更正版本。这确实节省了很多时间。

更新:

注意:Pycharm现在直接支持虚拟环境,对我来说似乎很好用-因此不再需要我的解决方法。

For Windows users when using PyCharm and a virtual environment under Windows, you can use the /k parameter to cmd.exe to set the virtual environment automatically.

Go to Settings, Terminal, Default shell and add /K <path-to-your-activate.bat>.

I don’t have the reputation to comment on the earlier response so posting this corrected version. This really saves a LOT of time.

Update:

Note: Pycharm now supports virtual environments directly and it seems to work well for me – so my workaround not needed anymore.


回答 3

根据彼得的回答和实验,我提出了一个很好的“一般解决方案”,可以解决以下问题:

  • 恢复登录外壳程序的行为。PyCharm通常运行登录外壳程序,但是–rcfile阻止了这种情况的发生。脚本仍然使用–rcfile,但是尝试模拟登录shell的INVOCATION行为。
  • 无需为每个环境创建rcfile
  • 如果您更改环境,则无需更新项目设置。

将此脚本放入bin目录中的某个位置。例如〜/ bin / pycharmactivate

if [ -r "/etc/profile" ] ; then . /etc/profile ; fi
if [ -r "~/.bash_profile" ] ; then
    . ~/.bash_profile
elif [ -r "~/.bash_login" ] ; then
    . ~/.bash_login
elif [ -r "~/.profile" ] ; then
    . ~/.profile
fi
ACTIVATERC=`cat .idea/workspace.xml | perl -n -e 'print "\$1/bin/activate" if m:option name="SDK_HOME" value="\\\$USER_HOME\\\$(.*)/bin/python":'`
if [ -n "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; else echo "Could not find virtualenv from PyCharm" ; fi

然后将PyCharm的Shell路径设置为:

/bin/bash --rcfile ~/bin/pycharmactivate

Based on answers from Peter and experimentation, I’ve come up with a good “general solution”, which solves the following:

  • Restores the behaviour of a login shell. PyCharm normally runs a login shell, but –rcfile stopped this happening. Script still uses –rcfile, but attempts to emulate the INVOCATION behaviour of a login shell.
  • Removes the need to create an rcfile for each environment
  • Removes the need to update the project settings if you change the environment.

Drop this script into a bin directory somewhere. E.g. ~/bin/pycharmactivate

if [ -r "/etc/profile" ] ; then . /etc/profile ; fi
if [ -r "~/.bash_profile" ] ; then
    . ~/.bash_profile
elif [ -r "~/.bash_login" ] ; then
    . ~/.bash_login
elif [ -r "~/.profile" ] ; then
    . ~/.profile
fi
ACTIVATERC=`cat .idea/workspace.xml | perl -n -e 'print "\$1/bin/activate" if m:option name="SDK_HOME" value="\\\$USER_HOME\\\$(.*)/bin/python":'`
if [ -n "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; else echo "Could not find virtualenv from PyCharm" ; fi

Then set PyCharm’s Shell path to:

/bin/bash --rcfile ~/bin/pycharmactivate

回答 4

PyCharm 4现在在IDE中集成了virtualenvs。选择项目解释器时,可以创建,添加或选择一个virtualenv。他们添加了一个在配置的项目解释器中运行的“ Python控制台”。

更多信息在这里。

PyCharm 4 now has virtualenvs integrated in the IDE. When selecting your project interpreter, you can create, add, or select a virtualenv. They’ve added a “Python Console” that runs in the configured project interpreter.

More info here.


回答 5

谢谢克里斯,您的脚本适用于某些项目,但不是我的机器上的全部。这是我编写的脚本,希望任何人都觉得它有用。

#Stored in ~/.pycharmrc 

ACTIVATERC=$(python -c 'import re
import os
from glob import glob

try:
  #sets Current Working Directory to _the_projects .idea folder
  os.chdir(os.getcwd()+"/.idea") 

  #gets every file in the cwd and sets _the_projects iml file
  for file in glob("*"): 
    if re.match("(.*).iml", file):
      project_iml_file = file

  #gets _the_virtual_env for _the_project
  for line in open(project_iml_file):
    env_name = re.findall("~/(.*)\" jdkType", line.strip())
    # created or changed a virtual_env after project creation? this will be true
    if env_name:
      print env_name[0] + "/bin/activate"
      break

    inherited = re.findall("type=\"inheritedJdk\"", line.strip())
    # set a virtual_env during project creation? this will be true
    if inherited:
      break

  # find _the_virtual_env in misc.xml
  if inherited:
    for line in open("misc.xml").readlines():
      env_at_project_creation = re.findall("\~/(.*)\" project-jdk", line.strip())
      if env_at_project_creation:
        print env_at_project_creation[0] + "/bin/activate"
        break
finally:
  pass
')

if [ "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; fi

Thanks Chris, your script worked for some projects but not all on my machine. Here is a script that I wrote and I hope anyone finds it useful.

#Stored in ~/.pycharmrc 

ACTIVATERC=$(python -c 'import re
import os
from glob import glob

try:
  #sets Current Working Directory to _the_projects .idea folder
  os.chdir(os.getcwd()+"/.idea") 

  #gets every file in the cwd and sets _the_projects iml file
  for file in glob("*"): 
    if re.match("(.*).iml", file):
      project_iml_file = file

  #gets _the_virtual_env for _the_project
  for line in open(project_iml_file):
    env_name = re.findall("~/(.*)\" jdkType", line.strip())
    # created or changed a virtual_env after project creation? this will be true
    if env_name:
      print env_name[0] + "/bin/activate"
      break

    inherited = re.findall("type=\"inheritedJdk\"", line.strip())
    # set a virtual_env during project creation? this will be true
    if inherited:
      break

  # find _the_virtual_env in misc.xml
  if inherited:
    for line in open("misc.xml").readlines():
      env_at_project_creation = re.findall("\~/(.*)\" project-jdk", line.strip())
      if env_at_project_creation:
        print env_at_project_creation[0] + "/bin/activate"
        break
finally:
  pass
')

if [ "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; fi

回答 6

我已经查看了上面所有的答案,但是没有一个对我来说足够优雅。在Pycharm 2017.1.3(在我的计算机中)中,最简单的方法是打开Settings->Tools->Terminal并检查Shell integrationActivate virtualenv选项。

I have viewed all of the answers above but none of them is elegant enough for me. In Pycharm 2017.1.3(in my computer), the easiest way is to open Settings->Tools->Terminal and check Shell integration and Activate virtualenv options.


回答 7

如果您使用的是Windows版本,则非常简单。如果您已经拥有虚拟环境,则只需导航至其文件夹,然后在文件夹activate.bat内找到即可Scripts。复制它的完整路径,并将其粘贴到pycharm的终端中,然后按Enter完成。

如果您需要创建新的虚拟环境:

转到“文件”>“设置”,然后搜索project interpreter,打开,单击齿轮按钮并在所需的位置创建环境,然后按照第一段进行操作。

If You are using windows version it is quite easy. If you already have the virtual environment just navigate to its folder, find activate.bat inside Scripts folder. copy it’s full path and paste it in pycharm’s terminal then press Enter and you’re done!

If you need to create new virtual environment :

Go to files > settings then search for project interpreter, open it, click on gear button and create the environment wherever you want and then follow first paragraph.


回答 8

在Mac上,它是PyCharm => Preferences … => Tools => Terminal => Activate virtualenv,默认情况下应启用。

On Mac it’s PyCharm => Preferences… => Tools => Terminal => Activate virtualenv, which should be enabled by default.


回答 9

我刚刚在主目录中添加了一个名为pycharmactivate的脚本。设置PyCharm(4.0.1)文件>设置>工具>终端> / bin / bash –rcfile〜/ pycharmactivate的Shell路径的值。如果您有不同的项目和virtualenv目录/名称,也许不是最好的解决方案,但是它对我有用。该脚本包含以下3行,并假定您的virtualenv与项目目录具有相同的名称。

source ~/.bashrc
projectdir=${PWD##*/}
source ~/.virtualenvs/$projectdir/bin/activate

I just added a script named pycharmactivate to my home directory. Set value of PyCharm (4.0.1) File > Settings > Tools > Terminal > Shell path to /bin/bash –rcfile ~/pycharmactivate. Maybe not the best solution incase you have different project and virtualenv directories/names but it works for me. This script contains the following 3 lines and assumes your virtualenv has the same name as your project dir.

source ~/.bashrc
projectdir=${PWD##*/}
source ~/.virtualenvs/$projectdir/bin/activate

回答 10

跟进Peter的回答,这里是.pycharmrc文件的Mac版本:

source /etc/profile
source ~/.bash_profile
source  <venv_dir>/bin/activate

母鸡

Following up on Peter’s answer, here the Mac version of the .pycharmrc file:

source /etc/profile
source ~/.bash_profile
source  <venv_dir>/bin/activate

Hen


回答 11

我有一个可以在Windows 7计算机上使用的解决方案。

我相信PyCharm的终端是它运行的结果,它将cmd.exe加载Windows PATH变量,并使用在其中首先找到的Python版本PATH。要编辑此变量,请右键单击我的电脑 -> 属性 -> 高级系统设置 -> 高级选项卡-> 环境变量…按钮。在“ 系统变量”部分中,选择并编辑PATH变量。

这是我编辑PATH 之前的相关部分:

C:\ Python27 \;
C:\ Python27 \ Lib \ site-packages \ pip \;
C:\ Python27 \ Scripts;
C:\ Python27 \ Lib \ site-packages \ django \ bin;

…并且编辑PATH(现在仅3行):

C:[project_path] \ virtualenv-Py2.7_Dj1.7 \ Lib \ site-packages \ pip;
C:[project_path] \ virtualenvs \ virtualenv-Py2.7_Dj1.7 \ Scripts;
C:[project_path] \ virtualenvs \ virtualenv-Py2.7_Dj1.7 \ Lib \ site-packages \ django \ bin;

要测试这一点,请打开一个新的 Windows终端(开始 ->键入cmd并点击Enter),看看它是否正在使用您的虚拟环境。如果可行,请重新启动PyCharm,然后在PyCharm的终端中对其进行测试。

I have a solution that worked on my Windows 7 machine.

I believe PyCharm’s terminal is a result of it running cmd.exe, which will load the Windows PATH variable, and use the version of Python that it finds first within that PATH. To edit this variable, right click My Computer –> Properties –> Advanced System Settings –> Advanced tab –> Environment Variables… button. Within the System variables section, select and edit the PATH variable.

Here is the relevant part of my PATH before editing:

C:\Python27\;
C:\Python27\Lib\site-packages\pip\;
C:\Python27\Scripts;
C:\Python27\Lib\site-packages\django\bin;

…and after editing PATH (only 3 lines now):

C:[project_path]\virtualenv-Py2.7_Dj1.7\Lib\site-packages\pip;
C:[project_path]\virtualenvs\virtualenv-Py2.7_Dj1.7\Scripts;
C:[project_path]\virtualenvs\virtualenv-Py2.7_Dj1.7\Lib\site-packages\django\bin;

To test this, open a new windows terminal (Start –> type in cmd and hit Enter) and see if it’s using your virtual environment. If that works, restart PyCharm and then test it out in PyCharm’s terminal.


回答 12

这就是我在做什么:在源代码文件夹中创建一个activate_env.bat(在Linux中为Windows,也许是.sh)文件:

/env_yourenvlocate/scripts/activate.bat

和另一个文件deactivate_env.bat:

/env_yourenvlocate/scripts/deactivate.bat

每次打开终端窗口时,只需执行bat文件来激活/停用virtualenv,您将停留在源代码路径中,而无需更改路径。

E:\Projects\django_study\src>active_env.bat

E:\Projects\django_study\src>../env_django_study/scripts/activate.bat
(env_django_study) E:\Projects\django_study\src>



(env_django_study) E:\Projects\django_study\src>deactive_env.bat

(env_django_study)E:\Projects\django_study\src>../env_django_study/scripts/deactivate.bat
E:\Projects\django_study\src>

this is what i am doing: create a activate_env.bat(windows,maybe .sh in linux) file in the source code folde:

/env_yourenvlocate/scripts/activate.bat

and another file deactivate_env.bat:

/env_yourenvlocate/scripts/deactivate.bat

everytime open the terminal window, just execute the bat file to activate/deactivate the virtualenv, you will stay in source code path, no need to change path to and back.

E:\Projects\django_study\src>active_env.bat

E:\Projects\django_study\src>../env_django_study/scripts/activate.bat
(env_django_study) E:\Projects\django_study\src>



(env_django_study) E:\Projects\django_study\src>deactive_env.bat

(env_django_study)E:\Projects\django_study\src>../env_django_study/scripts/deactivate.bat
E:\Projects\django_study\src>

回答 13

如果您的Pycharm 2016.1.4v及更高版本应使用 "default path" /K "<path-to-your-activate.bat>" 不要忘记引号

If your Pycharm 2016.1.4v and higher you should use "default path" /K "<path-to-your-activate.bat>" don’t forget quotes


回答 14

如果您已将项目移动到另一个目录,则可以通过“设置”对话框设置新路径。然后,您需要在“编辑配置”对话框中设置此项目解释器。

If you have moved your project to another directory, you can set the new path via Settings dialog. And then you need to set this Project Interpreter in the Edit Configuration dialog.


回答 15

另一种选择是使用virtualenvwrapper来管理您的虚拟环境。看来,一旦virtualenvwrapper 脚本被激活,pycharm就可以使用它,然后workon从pycharm控制台可以使用简单的命令,并为您提供可用的虚拟环境:

kevin@debian:~/Development/django-tutorial$ workon
django-tutorial
FlaskHF
SQLAlchemy
themarkdownapp
kevin@debian:~/Development/django-tutorial$ workon django-tutorial
(django-tutorial)kevin@debian:~/Development/django-tutorial$ 

Another alternative is to use virtualenvwrapper to manage your virtual environments. It appears that once the virtualenvwrapper script is activated, pycharm can use that and then the simple workon command will be available from the pycharm console and present you with the available virtual environments:

kevin@debian:~/Development/django-tutorial$ workon
django-tutorial
FlaskHF
SQLAlchemy
themarkdownapp
kevin@debian:~/Development/django-tutorial$ workon django-tutorial
(django-tutorial)kevin@debian:~/Development/django-tutorial$ 

回答 16

该方法应该在每个项目的任意虚拟环境下都可以使用,并且由于使用创建的钩子,因此不会对您的环境做任何假设。

你写:

  • 调用钩子的全局脚本
  • 每个PyCharm项目的挂钩脚本(不是必需的)

鉴于当前最新的PyCharm(社区2016.1)不允许每个项目的终端设置都调用项目特定挂钩的脚本开头。这是我的~/.pycharmrc

if [ -r ".pycharm/term-activate" ]; then
   echo "Terminal activation hook detected."
   echo "Loading Bash profile..."
   source ~/.bash_profile
   echo "Activating terminal hook..."
   source ".pycharm/term-activate"
   source activate $PYCHARM_VENV
fi

如果您使用的不是Bash,.bash_profile则应调用自己的等效项。

现在,将PyCharm设置为“工具->终端->外壳路径”以调用此脚本,例如: /bin/bash --rcfile ~/.pycharmrc

最后,对于每个PyCharm项目,您都需要激活特定的虚拟环境,请在PyCharm项目root内创建一个文件.pycharm/term-activate。这是您的钩子,它将仅为您的PyCharm项目定义所需的虚拟环境的名称:

export PYCHARM_VENV=<your-virtual-env-name>

当然,您可以使用在您的特定PyCharm项目的终端环境中发现有用的任何东西来扩展自己的功能。

This method should work with arbitrary virtual environments per project and it doesn’t make assumptions on your environment as it is using hooks you create.

You write:

  • A global script that invokes the hook
  • A hook script per PyCharm project (not mandatory)

Given that the current latest PyCharm (Community 2016.1) does not allow for Terminal settings per project start with the script that invokes the project specific hook. This is my ~/.pycharmrc:

if [ -r ".pycharm/term-activate" ]; then
   echo "Terminal activation hook detected."
   echo "Loading Bash profile..."
   source ~/.bash_profile
   echo "Activating terminal hook..."
   source ".pycharm/term-activate"
   source activate $PYCHARM_VENV
fi

If you are using something other than Bash, invoke your own .bash_profile equivalent should you wish to.

Now set your PyCharm “Tools -> Terminal -> Shell Path” to invoke this script, e.g.: /bin/bash --rcfile ~/.pycharmrc

Finally, for every PyCharm project you need a specific virtual environment activated, create a file within the PyCharm project root .pycharm/term-activate. This is your hook and it will simply define the name of the desired virtual environment for your PyCharm project:

export PYCHARM_VENV=<your-virtual-env-name>

You can of course extend your hooks with anything you find useful in the terminal environment of your particular PyCharm project.


回答 17

对于Windows上的conda虚拟环境,请确保未命名您的批处理文件,activate.bat因为这将导致与conda activate命令冲突,从而导致对该批处理文件的递归调用。

下面的Shell路径对我有用:

"cmd.exe" /k ""C:\FullPathToYourProject\activate-env.bat""

并在activate-env.bat文件中:

call activate myenvname

For conda virtual environments on Windows, make sure your batch file is NOT named activate.bat as this will cause a conflict with the conda activate command, resulting in a recursive calling of the batch file.

What works for me is the following Shell path:

"cmd.exe" /k ""C:\FullPathToYourProject\activate-env.bat""

And in the activate-env.bat file:

call activate myenvname

回答 18

我希望为每个项目提供一个单独的虚拟环境,并且不太在乎是否需要其他文件来简化此工作。您只需执行一次即可用于所有项目的解决方案,然后将以下内容添加到您的.bashrc或中.bash_profile

if [ -d "./venv" ]; then
    source ./venv/bin/activate
fi

这将检查是否存在打开终端的虚拟环境,是否激活了终端(当然可以使用其他相对路径)。PyCharm的终端设置可以保留为默认设置。

I wanted a separate virtual environment for each project, and didn’t care much for having additional files to facilitate this. A solution which you only need to do once and works for all projects is then adding the following to your .bashrc or .bash_profile:

if [ -d "./venv" ]; then
    source ./venv/bin/activate
fi

This checks if there is a virtual environment where the terminal is being opened, and if so activates it (and of course other relative paths could be used). PyCharm’s terminal settings can be left as their default.


回答 19

PyCharm 4.5.4

使用以下内容在主文件夹中创建文件.pycharmrc

source ~/.bashrc
source ~/pycharmvenv/bin/activate

使用您的virtualenv路径作为最后一个参数。

然后将Shell Preferences-> Project Settings-> Shell path设置为

/bin/bash --rcfile ~/.pycharmrc

我不知道为什么,但这对我不起作用。PyCharm打印错误。

cmd.exe /K "<path-to-your-activate.bat>" 它可以工作,但是即使没有必要,它也会为每个项目创建相同的virtualenv。

收据有效!但是字符串/env_yourenvlocate/scripts/activate.bat必须包含引号,像这样"Full_path_to_your_env_locate\scripts\activate.bat"

禁用virtualenv非常容易-在终端中输入’deactivate’

(virt_env) D:\Projects\src>deactivate
D:\Projects\src>

PyCharm 4.5.4

Create a file .pycharmrc in your home folder with the following contents

source ~/.bashrc
source ~/pycharmvenv/bin/activate

Using your virtualenv path as the last parameter.

Then set the shell Preferences->Project Settings->Shell path to

/bin/bash --rcfile ~/.pycharmrc

I don’t why, but it doesn’t work for me. PyCharm prints an error.

cmd.exe /K "<path-to-your-activate.bat>" It works, but it creates the same virtualenv for each project, and even if this is not necessary.

This receipt is working! But the string /env_yourenvlocate/scripts/activate.bat must contain quotes, like this "Full_path_to_your_env_locate\scripts\activate.bat"!

Deactivate the virtualenv is very easy – type in the terminal ‘deactivate’

(virt_env) D:\Projects\src>deactivate
D:\Projects\src>

回答 20

WSL解决方案(Windows上的Ubuntu)

如果您使用的是WSL(在Windows上为Ubuntu),则还可以在pycharm中将bash作为终端打开,并激活linux virtualenv。

使用.pycharmrc类似于Peter Gibson答案中所述的文件;将.pycharmrc文件添加到您的主目录,其中包含以下内容:

source ~/.bashrc
source ~/path_to_virtualenv/bin/activate

在Pycharm 文件>设置>工具>终端中,添加以下“外壳路径”:

"C:/Windows/system32/bash.exe" -c "bash --rcfile ~/.pycharmrc"


项目特定的virtualenv

您的virtualenv的路径.pycharmrc不必是绝对的。您可以通过在项目目录中设置相对路径来设置特定于项目的virtualenv。我的virtualenv始终位于项目目录下的“ venv”文件夹中,因此.pycharmrc文件如下所示:

来源〜/ .bashrc
源〜/ pycharmvenv / bin / activate#绝对路径
源./venv/bin/activate#相对路径


奖励:自动打开ssh隧道以将virtualenv连接为项目解释器

将以下内容添加到您的.pycharmrc文件中:

if [ $(ps -aux | grep -c 'ssh') -lt 2 ]; then
    sudo service ssh start 
fi

这将检查ssh隧道是否已经打开,否则打开一个。在 Pycharm的“文件”->“设置”->“项目”->“项目解释器”中,添加具有以下配置的新远程解释器:

+ -------------------------- + ---------------------- ----------- + ------- + ---- +
| 名称:<口译员名称> | | |
| 选择| “ SSH凭证” | | |
| 主持人:127.0.0.1 | 端口:| 22 |
| 用户:| <Linux用户名> | | |
| 验证类型:| “密码” | | |
| 密码:<Linux密码> | | |
| Python解释器路径:<Linux到您的virtualenv的路径> | | |
| Python帮助程序路径:| <自动设置> | | |
+ -------------------------- + ---------------------- ----------- + ------- + ---- +

现在,当您打开项目时,bash会自动在virtualenv中启动,打开ssh隧道,并且pycharm将virtualenv连接为远程解释器。

警告:Windows中的最新更新将在启动时自动启动SshBroker和SshProxy服务。这些阻止了从Linux到Windows的ssh隧道。您可以在“任务管理器”->“服务”中停止这些服务,然后所有内容将再次运行。

Solution for WSL (Ubuntu on Windows)

If you’re using WSL (Ubuntu on Windows), you can also open bash as terminal in pycharm and activate a linux virtualenv.

Use a .pycharmrc file like described in Peter Gibson’s answer; Add the .pycharmrc file to your home directory with following content:

source ~/.bashrc
source ~/path_to_virtualenv/bin/activate

In Pycharm File > Settings > Tools > Terminal add the following ‘Shell path’:

"C:/Windows/system32/bash.exe" -c "bash --rcfile ~/.pycharmrc"


Project specific virtualenv

The path to your virtualenv in .pycharmrc does not have to be absolute. You can set a project specific virtualenv by setting a relative path from your project directory. My virtualenv is always located in a ‘venv’ folder under my project directory, so my .pycharmrc file looks like this:

source ~/.bashrc
source ~/pycharmvenv/bin/activate #absolute path
source ./venv/bin/activate #relative path


BONUS: automatically open ssh tunnel to connect virtualenv as project interpreter

Add the following to your .pycharmrc file:

if [ $(ps -aux | grep -c 'ssh') -lt 2 ]; then
    sudo service ssh start 
fi

This checks if a ssh tunnel is already opened, and opens one otherwise. In File -> Settings -> Project -> Project Interpreter in Pycharm, add a new remote interpreter with following configuration:

+--------------------------+---------------------------------+-------+----+
| Name:                    | <Interpreter name>              |       |    |
| Select                   | 'SSH Credentials'               |       |    |
| Host:                    | 127.0.0.1                       | Port: | 22 |
| User:                    | <Linux username>                |       |    |
| Auth type:               | 'Password'                      |       |    |
| Password:                | <Linux password>                |       |    |
| Python interpreter path: | <Linux path to your virtualenv> |       |    |
| Python helpers path:     | <Set automatically>             |       |    |
+--------------------------+---------------------------------+-------+----+

Now when you open your project, your bash automatically starts in your virtualenv, opens a ssh tunnel, and pycharm connects the virtualenv as remote interpreter.

warning: the last update in Windows automatically starts a SshBroker and SshProxy service on startup. These block the ssh tunnel from linux to windows. You can stop these services in Task Manager -> Services, after which everything will work again.


回答 21

输入终端>运行>调试>编辑配置时,您有一个选择

选择合适的conda环境。。同样,在创建新项目时-它要求配置该位置。

One option you have when you enter the terminal > Run > Debug > Edit Configurations

select the appropriate conda environmnent.. Also when you create a new project – it asks to configure this location.


自定义代码在virtualenv中的什么位置?

问题:自定义代码在virtualenv中的什么位置?

使用时应该遵循哪种目录结构virtualenv?例如,如果我正在构建WSGI应用程序并创建了一个名为virtualenv的虚拟环境,那么foobar我将从以下目录结构开始:

/foobar
  /bin
    {activate, activate.py, easy_install, python}
  /include
    {python2.6/...}
  /lib
    {python2.6/...}

创建此环境后,将在哪里放置自己的环境:

  • python文件?
  • 静态文件(图像/等)?
  • “自定义”程序包,例如在线提供但在奶酪店中找不到的程序包?

关于virtualenv目录?

(假设我已经知道virtualenv目录本身应该在哪里。)

What sort of directory structure should one follow when using virtualenv? For instance, if I were building a WSGI application and created a virtualenv called foobar I would start with a directory structure like:

/foobar
  /bin
    {activate, activate.py, easy_install, python}
  /include
    {python2.6/...}
  /lib
    {python2.6/...}

Once this environment is created, where would one place their own:

  • python files?
  • static files (images/etc)?
  • “custom” packages, such as those available online but not found in the cheese-shop?

in relation to the virtualenv directories?

(Assume I already know where the virtualenv directories themselves should go.)


回答 0

virtualenv提供python解释器实例,而不是应用程序实例。通常,您不会在包含系统默认Python的目录中创建应用程序文件,同样,也无需在virtualenv目录中定位应用程序。

例如,您可能有一个项目,其中有多个使用同一virtualenv的应用程序。或者,您可能正在使用virtualenv测试应用程序,该应用程序随后将与系统Python一起部署。或者,您可能正在打包一个独立的应用程序,在该应用程序中,将virtualenv目录放置在应用程序目录本身内的某个位置可能很有意义。

因此,总的来说,我认为这个问题没有一个正确的答案。而且,一件好事virtualenv是它支持许多不同的用例:不需要有正确的方法。

virtualenv provides a python interpreter instance, not an application instance. You wouldn’t normally create your application files within the directories containing a system’s default Python, likewise there’s no requirement to locate your application within a virtualenv directory.

For example, you might have a project where you have multiple applications using the same virtualenv. Or, you may be testing an application with a virtualenv that will later be deployed with a system Python. Or, you may be packaging up a standalone app where it might make sense to have the virtualenv directory located somewhere within the app directory itself.

So, in general, I don’t think there is one right answer to the question. And, a good thing about virtualenv is that it supports many different use cases: there doesn’t need to be one right way.


回答 1

如果您经常只有几个项目,那么没有什么可以阻止您为每个项目创建一个新的virtualenv并将包放入其中:

/foobar
  /bin
    {activate, activate.py, easy_install, python}
  /include
    {python2.6/...}
  /lib
    {python2.6/...}
  /mypackage1
    __init__.py
  /mypackage2
    __init__.py

这种方法的优点是,您始终可以确保找到属于该项目的激活脚本。

$ cd /foobar
$ source bin/activate
$ python 
>>> import mypackage1
>>>

如果您决定更加有条理,则应考虑将所有virtualenvs放在一个文件夹中,并以您正在处理的项目命名。

  /virtualenvs
    /foobar
      /bin
        {activate, activate.py, easy_install, python}
      /include
        {python2.6/...}
      /lib
        {python2.6/...}
  /foobar
    /mypackage1
      __init__.py
    /mypackage2
      __init__.py

这样,当出现问题时,您始终可以从新的virtualenv重新开始,并且项目文件保持安全。

另一个优点是您的多个项目可以使用相同的virtualenv,因此如果您有很多依赖项,则不必一遍又一遍地进行相同的安装。

$ cd /foobar
$ source ../virtualenvs/foobar/bin/activate
$ python 
>>> import mypackage2
>>>

对于经常需要设置和关闭virtualenvs的用户,看一下virtualenvwrapper很有意义。

http://pypi.python.org/pypi/virtualenvwrapper

借助virtualenvwrapper,您可以

* create and delete virtual environments

* organize virtual environments in a central place

* easily switch between environments

在项目“ foo”和“ bar”上工作时,您无需再担心virtualenvs的位置:

  /foo
    /mypackage1
      __init__.py
  /bar
    /mypackage2
      __init__.py

这是您开始处理项目“ foo”的方式:

$ cd foo
$ workon
bar
foo
$ workon foo
(foo)$ python
>>> import mypackage1
>>>

然后,切换到项目“ bar”非常简单:

$ cd ../bar
$ workon bar
(bar)$ python
>>> import mypackage2
>>>

很整洁,不是吗?

If you only have a few projects every so often, nothing stops you from creating a new virtualenv for each one, and putting your packages right inside:

/foobar
  /bin
    {activate, activate.py, easy_install, python}
  /include
    {python2.6/...}
  /lib
    {python2.6/...}
  /mypackage1
    __init__.py
  /mypackage2
    __init__.py

The advantage of this approach is that you can always be sure to find find the activate script that belongs to the project inside.

$ cd /foobar
$ source bin/activate
$ python 
>>> import mypackage1
>>>

If you decide to be a bit more organized, you should consider putting all your virtualenvs into one folder, and name each of them after the project you are working on.

  /virtualenvs
    /foobar
      /bin
        {activate, activate.py, easy_install, python}
      /include
        {python2.6/...}
      /lib
        {python2.6/...}
  /foobar
    /mypackage1
      __init__.py
    /mypackage2
      __init__.py

This way you can always start over with a new virtualenv when things go wrong, and your project files stay safe.

Another advantage is that several of your projects can use the same virtualenv, so you don’t have to do the same installation over and over if you have a lot of dependencies.

$ cd /foobar
$ source ../virtualenvs/foobar/bin/activate
$ python 
>>> import mypackage2
>>>

For users that regularly have to set up and tear down virtualenvs it would make sense to look at virtualenvwrapper.

http://pypi.python.org/pypi/virtualenvwrapper

With virtualenvwrapper you can

* create and delete virtual environments

* organize virtual environments in a central place

* easily switch between environments

You no more have to worry about where your virtualenvs are when working on the projects “foo” and “bar”:

  /foo
    /mypackage1
      __init__.py
  /bar
    /mypackage2
      __init__.py

This is how you start working on project “foo”:

$ cd foo
$ workon
bar
foo
$ workon foo
(foo)$ python
>>> import mypackage1
>>>

Then switching to project “bar” is as simple as this:

$ cd ../bar
$ workon bar
(bar)$ python
>>> import mypackage2
>>>

Pretty neat, isn’t it?


回答 2

因为virtualenvs不可重定位,所以我认为将项目文件放在virtualenv目录中是不明智的做法。virtualenv本身是一个生成的开发/部署工件(有点像.pyc文件),而不是项目的一部分;应该很容易将其吹散并随时重新创建,或者在新的部署主机上创建一个新的,等等。

实际上,许多人都使用virtualenvwrapper,它几乎完全从您的意识中删除了实际的virtualenvs,默认情况下将它们全部并排放置在$ HOME / .virtualenvs中。

Because virtualenvs are not relocatable, in my opinion it is bad practice to place your project files inside a virtualenv directory. The virtualenv itself is a generated development/deployment artifact (sort of like a .pyc file), not part of the project; it should be easy to blow it away and recreate it anytime, or create a new one on a new deploy host, etc.

Many people in fact use virtualenvwrapper, which removes the actual virtualenvs from your awareness almost completely, placing them all side-by-side in $HOME/.virtualenvs by default.


回答 3

如果您为您的项目指定setup.py,则pip可以直接从版本控制中导入它。

做这样的事情:

$ virtualenv --no-site-packages myproject
$ . myproject/bin/activate
$ easy_install pip
$ pip install -e hg+http://bitbucket.org/owner/myproject#egg=proj

-e将投入该项目myproject/src,但它链接到myproject/lib/pythonX.X/site-packages/,所以所做的任何更改将得到回升立即从本地导入模块site-packages。的#egg位告诉pip您要给它为您创建的鸡蛋包装取什么名字。

如果您不使用--no-site-packages,请谨慎指定要使用-E选项将pip安装到virtualenv中

If you give your project a setup.py, pip can import it from version control directly.

Do something like this:

$ virtualenv --no-site-packages myproject
$ . myproject/bin/activate
$ easy_install pip
$ pip install -e hg+http://bitbucket.org/owner/myproject#egg=proj

The -e will put the project in myproject/src, but link it to myproject/lib/pythonX.X/site-packages/, so any changes you make will get picked up immediately in modules that import it from your local site-packages. The #egg bit tells pip what name you want to give to the egg package it creates for you.

If you don’t use --no-site-packages, be careful to specify that you want pip to install into the virtualenv with the -E option


应该在哪里创建virtualenvs?

问题:应该在哪里创建virtualenvs?

我对应该在哪里放置我的虚拟环境感到困惑。

在我的第一个django项目中,我使用以下命令创建了该项目

django-admin.py startproject djangoproject

然后,我进入djangoproject目录并运行命令

virtualenv env

在与内部djangoproject目录相同级别上创建了虚拟环境目录。

这是为特定项目创建virtualenv的错误位置吗?

我给人的印象是,大多数人将所有virtualenv放在一个完全不同的目录中,例如~/virtualenvs,然后使用virtualenvwrapper在它们之间来回切换。

有正确的方法吗?

I’m confused as to where I should put my virtualenvs.

With my first django project, I created the project with the command

django-admin.py startproject djangoproject

I then cd’d into the djangoproject directory and ran the command

virtualenv env

which created the virtual environment directory at the same level as the inner djangoproject directory.

Is this the wrong place in which to create the virtualenv for this particular project?

I’m getting the impression that most people keep all their virtualenvs together in an entirely different directory, e.g. ~/virtualenvs, and then use virtualenvwrapper to switch back and forth between them.

Is there a correct way to do this?


回答 0

许多人使用virtualenvwrapper工具,该工具将所有virtualenvs保留在同一位置(~/.virtualenvs目录),并允许在其中创建和保存它们的快捷方式。例如,您可以这样做:

mkvirtualenv djangoproject

然后再:

workon djangoproject

将virtualenv目录保留在项目本身中可能是一个坏主意,因为您不想分发它(它可能特定于您的计算机或操作系统)。而是使用pip保留一个requirements.txt文件:

pip freeze > requirements.txt

并分发。这将允许使用您的项目的其他人使用以下命令将所有相同的要求重新安装到他们的virtualenv中:

pip install -r requirements.txt

Many people use the virtualenvwrapper tool, which keeps all virtualenvs in the same place (the ~/.virtualenvs directory) and allows shortcuts for creating and keeping them there. For example, you might do:

mkvirtualenv djangoproject

and then later:

workon djangoproject

It’s probably a bad idea to keep the virtualenv directory in the project itself, since you don’t want to distribute it (it might be specific to your computer or operating system). Instead, keep a requirements.txt file using pip:

pip freeze > requirements.txt

and distribute that. This will allow others using your project to reinstall all the same requirements into their virtualenv with:

pip install -r requirements.txt

回答 1

更改virtualenv目录的位置会破坏它

这是把仓库树,例如目录以外的下一个优势~/.virtualenvsvirutalenvwrapper

否则,如果将其保留在项目树中,则移动项目位置将破坏virtualenv。

请参阅:重命名virtualenv文件夹而不破坏它

有,--relocatable但是众所周知它并不完美。

另一个次要优势:您不必这样做.gitignore

将其忽略到项目树本身的好处是:

  • 使相关的东西保持在一起。
  • 您可能永远不会在项目之间重用给定的virtualenv,因此将其放置在其他位置不会带来太多优势

Changing the location of the virtualenv directory breaks it

This is one advantage of putting the directory outside of the repository tree, e.g. under ~/.virtualenvs with virutalenvwrapper.

Otherwise, if you keep it in the project tree, moving the project location will break the virtualenv.

See: Renaming a virtualenv folder without breaking it

There is --relocatable but it is known to not be perfect.

Another minor advantage: you don’t have to .gitignore it.

The advantages of putting it gitignored in the project tree itself are:

  • keeps related stuff close together.
  • you will likely never reuse a given virtualenv across projects, so putting it somewhere else does not give much advantage

回答 2

通常放置它们的位置与virtualenvwrapper的默认安装放置它们的位置相同: ~/.virtualenvs

相关:virtualenvwrapper是一个出色的工具,可为常用的virtualenv命令提供简写。http://www.doughellmann.com/projects/virtualenvwrapper/

The generally accepted place to put them is the same place that the default installation of virtualenvwrapper puts them: ~/.virtualenvs

Related: virtualenvwrapper is an excellent tool that provides shorthands for the common virtualenv commands. http://www.doughellmann.com/projects/virtualenvwrapper/


回答 3

如果使用pyenv install Python,则pyenv-virtualenv将是最佳做法。如果设置了.python-version文件,则可以在更改工作文件夹时自动激活或停用虚拟环境。Pyenv-virtualenv还将所有虚拟环境放入$HOME/.pyenv/versions文件夹中。

If you use pyenv install Python, then pyenv-virtualenv will be a best practice. If set .python-version file, it can auto activate or deactivate virtual env when you change work folder. Pyenv-virtualenv also put all virtual env into $HOME/.pyenv/versions folder.


回答 4

根据我的个人经验,我建议将所有虚拟环境组织在一个目录中。除非有人具有非常敏锐的内存并且可以记住分散在整个文件系统中的文件/文件夹。不太喜欢仅使用其他工具来管理虚拟环境。在VSCode中,如果我的configure(python.venvPath)目录包含所有虚拟环境,则它可以自动识别所有虚拟环境。

From my personal experience, I would recommend to organize all virtual environments in one single directory. Unless someone has extremely sharp memory and can remember files/folders scattered across file system. Not a big fan of using other tools just to mange virtual environments. In VSCode if I configure(python.venvPath) directory containing all virtual environments, it can automatically recognize all of them.


使用virtualenv进行pip安装Matplotlib错误

问题:使用virtualenv进行pip安装Matplotlib错误

我正在尝试在新的virtualenv中安装matplotlib。

当我做:

pip install matplotlib

要么

pip install http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz

我收到此错误:

building 'matplotlib._png' extension

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -fPIC -  DPY_ARRAY_UNIQUE_SYMBOL=MPL_ARRAY_API -DPYCXX_ISO_CPP_LIB=1 -I/usr/local/include -I/usr/include -I. -I/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/numpy/core/include -I. -I/usr/include/python2.7 -c src/_png.cpp -o build/temp.linux-x86_64-2.7/src/_png.o

src/_png.cpp:10:20: fatal error: png.h: No such file or directory

compilation terminated.

error: command 'gcc' failed with exit status 1

有人知道发生了什么吗?

任何帮助,不胜感激。

I am trying to install matplotlib in a new virtualenv.

When I do:

pip install matplotlib

or

pip install http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/matplotlib-1.1.0.tar.gz

I get this error:

building 'matplotlib._png' extension

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -fPIC -  DPY_ARRAY_UNIQUE_SYMBOL=MPL_ARRAY_API -DPYCXX_ISO_CPP_LIB=1 -I/usr/local/include -I/usr/include -I. -I/home/sam/django-projects/datazone/local/lib/python2.7/site-packages/numpy/core/include -I. -I/usr/include/python2.7 -c src/_png.cpp -o build/temp.linux-x86_64-2.7/src/_png.o

src/_png.cpp:10:20: fatal error: png.h: No such file or directory

compilation terminated.

error: command 'gcc' failed with exit status 1

Anyone have an idea what is going on?

Any help much appreciated.


回答 0

构建Matplotlib需要libpngfreetype以及)不是python库,因此pip无法处理(或freetype)安装它。

您需要按照libpng-develfreetype-devel(或与您的操作系统等效的其他方式)安装一些东西。

请参阅matplotlib 的构建要求/说明

Building Matplotlib requires libpng (and freetype, as well) which isn’t a python library, so pip doesn’t handle installing it (or freetype).

You’ll need to install something along the lines of libpng-devel and freetype-devel (or whatever the equivalent is for your OS).

See the building requirements/instructions for matplotlib.


回答 1

要生成png格式的图形,您需要安装以下依赖包

sudo apt-get install libpng-dev
sudo apt-get install libfreetype6-dev

Ubuntu https://apps.ubuntu.com/cat/applications/libpng12-0/ 或使用以下命令

sudo apt-get install libpng12-0

To generate graph in png format you need to Install following dependent packages

sudo apt-get install libpng-dev
sudo apt-get install libfreetype6-dev

Ubuntu https://apps.ubuntu.com/cat/applications/libpng12-0/ or using following command

sudo apt-get install libpng12-0

回答 2

由于我两次都在这个问题上苦苦挣扎(即使在全新安装kubuntu 15.04之后),而安装freetype也解决不了任何问题,因此我进行了进一步调查。

解决方案:
来自github问题:

仅当未安装pkg-config时,才会发生此错误;
现在,简单的操作
sudo apt-get install pkg-config
将支持包含路径。

安装完成后顺利进行。

As I have struggled with this issue twice (even after fresh kubuntu 15.04 install) and installing freetype did not solve anything, I investigated further.

The solution:
From github issue:

This bug only occurs if pkg-config is not installed;
a simple
sudo apt-get install pkg-config
will shore up the include paths for now.

After this installation proceeds smoothly.


回答 3

作为补充,在Amazon EC2上,我需要做的是:

sudo yum install freetype-devel
sudo yum install libpng-devel
sudo pip install matplotlib

As a supplementary, on Amazon EC2, what I need to do is:

sudo yum install freetype-devel
sudo yum install libpng-devel
sudo pip install matplotlib

回答 4

在OSX上,我可以通过以下方式安装matplotlib:

pip install matplotlib==1.4.0

只有在我跑完之后:

brew install freetype

On OSX I was able to get matplotlib to install via:

pip install matplotlib==1.4.0

only after I ran:

brew install freetype

回答 5

在Windows下,这对我有用:

python -m pip install -U pip setuptools
python -m pip install matplotlib

(来自https://matplotlib.org/users/installing.html

Under Windows this worked for me:

python -m pip install -U pip setuptools
python -m pip install matplotlib

(from https://matplotlib.org/users/installing.html)


回答 6

sudo apt-get install libpng-dev libjpeg8-dev libfreetype6-dev

在Ubuntu 14.04上为我工作

sudo apt-get install libpng-dev libjpeg8-dev libfreetype6-dev

worked for me on Ubuntu 14.04


回答 7

以上答案均不适用于Mint,因此我做到了:

sudo apt-get install build-essential g++

None of the above answers worked for me in Mint, so I did:

sudo apt-get install build-essential g++

回答 8

如果在MacOSx上尝试

xcode-select --install

这符合subprocess 32,失败的原因。

If on MacOSx try

xcode-select --install

This complies subprocess 32, the reason for the failure.


回答 9

要减少安装所需的软件包,您只需要

apt-get install -y \
    libfreetype6-dev \
    libxft-dev && \
    pip install matplotlib

您将在本地安装以下软件包

Collecting matplotlib
  Downloading matplotlib-2.2.0-cp35-cp35m-manylinux1_x86_64.whl (12.5MB)
Collecting pytz (from matplotlib)
  Downloading pytz-2018.3-py2.py3-none-any.whl (509kB)
Collecting python-dateutil>=2.1 (from matplotlib)
  Downloading python_dateutil-2.6.1-py2.py3-none-any.whl (194kB)
Collecting pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 (from matplotlib)
  Downloading pyparsing-2.2.0-py2.py3-none-any.whl (56kB)
Requirement already satisfied: six>=1.10 in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages (from matplotlib)
Collecting cycler>=0.10 (from matplotlib)
  Downloading cycler-0.10.0-py2.py3-none-any.whl
Collecting kiwisolver>=1.0.1 (from matplotlib)
  Downloading kiwisolver-1.0.1-cp35-cp35m-manylinux1_x86_64.whl (949kB)
Requirement already satisfied: numpy>=1.7.1 in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages (from matplotlib)
Requirement already satisfied: setuptools in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages/setuptools-27.2.0-py3.5.egg (from kiwisolver>=1.0.1->matplotlib)
Installing collected packages: pytz, python-dateutil, pyparsing, cycler, kiwisolver, matplotlib
Successfully installed cycler-0.10.0 kiwisolver-1.0.1 matplotlib-2.2.0 pyparsing-2.2.0 python-dateutil-2.6.1 pytz-2018.3

To reduce the required packages to install you just need

apt-get install -y \
    libfreetype6-dev \
    libxft-dev && \
    pip install matplotlib

and you will get the following packages locally installed

Collecting matplotlib
  Downloading matplotlib-2.2.0-cp35-cp35m-manylinux1_x86_64.whl (12.5MB)
Collecting pytz (from matplotlib)
  Downloading pytz-2018.3-py2.py3-none-any.whl (509kB)
Collecting python-dateutil>=2.1 (from matplotlib)
  Downloading python_dateutil-2.6.1-py2.py3-none-any.whl (194kB)
Collecting pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 (from matplotlib)
  Downloading pyparsing-2.2.0-py2.py3-none-any.whl (56kB)
Requirement already satisfied: six>=1.10 in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages (from matplotlib)
Collecting cycler>=0.10 (from matplotlib)
  Downloading cycler-0.10.0-py2.py3-none-any.whl
Collecting kiwisolver>=1.0.1 (from matplotlib)
  Downloading kiwisolver-1.0.1-cp35-cp35m-manylinux1_x86_64.whl (949kB)
Requirement already satisfied: numpy>=1.7.1 in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages (from matplotlib)
Requirement already satisfied: setuptools in /opt/conda/envs/pytorch-py35/lib/python3.5/site-packages/setuptools-27.2.0-py3.5.egg (from kiwisolver>=1.0.1->matplotlib)
Installing collected packages: pytz, python-dateutil, pyparsing, cycler, kiwisolver, matplotlib
Successfully installed cycler-0.10.0 kiwisolver-1.0.1 matplotlib-2.2.0 pyparsing-2.2.0 python-dateutil-2.6.1 pytz-2018.3

回答 10

另一个选择是安装anaconda,该软件包随附以下软件包:Matplotlib,numpy和pandas。

https://anaconda.org

Another option is to install anaconda, which comes with packages such as: Matplotlib, numpy and pandas.

https://anaconda.org


如何在已经创建的virtualenv中设置pythonpath?

问题:如何在已经创建的virtualenv中设置pythonpath?

我要编辑什么文件?我创建了一个虚拟环境。

What file do I edit, and how? I created a virtual environment.


回答 0

编辑#2

正确的答案是@arogachev的答案。


如果要更改PYTHONPATHvirtualenv中使用的名称,可以将以下行添加到virtualenv的bin/activate文件中:

export PYTHONPATH="/the/path/you/want"

这样,PYTHONPATH每次使用此virtualenv时都会设置新的。

编辑:( 回答@RamRachum的评论)

要将其恢复到的原始值deactivate,您可以添加

export OLD_PYTHONPATH="$PYTHONPATH"

在前面提到的行之前,然后将以下行添加到bin/postdeactivate脚本中。

export PYTHONPATH="$OLD_PYTHONPATH"

EDIT #2

The right answer is @arogachev’s one.


If you want to change the PYTHONPATH used in a virtualenv, you can add the following line to your virtualenv’s bin/activate file:

export PYTHONPATH="/the/path/you/want"

This way, the new PYTHONPATH will be set each time you use this virtualenv.

EDIT: (to answer @RamRachum’s comment)

To have it restored to its original value on deactivate, you could add

export OLD_PYTHONPATH="$PYTHONPATH"

before the previously mentioned line, and add the following line to your bin/postdeactivate script.

export PYTHONPATH="$OLD_PYTHONPATH"

回答 1

@ s29的评论应该是一个答案:

向虚拟环境添加目录的一种方法是安装virtualenvwrapper(这对很多事情都有用),然后执行

mkvirtualenv myenv
workon myenv
add2virtualenv . #for current directory
add2virtualenv ~/my/path

如果要删除这些路径,请编辑文件 myenvhomedir/lib/python2.7/site-packages/_virtualenv_path_extensions.pth

有关virtualenvwrapper的文档可以在http://virtualenvwrapper.readthedocs.org/en/latest/中找到。

有关此功能的特定文档,请访问 http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html?highlight=add2virtualenv

The comment by @s29 should be an answer:

One way to add a directory to the virtual environment is to install virtualenvwrapper (which is useful for many things) and then do

mkvirtualenv myenv
workon myenv
add2virtualenv . #for current directory
add2virtualenv ~/my/path

If you want to remove these path edit the file myenvhomedir/lib/python2.7/site-packages/_virtualenv_path_extensions.pth

Documentation on virtualenvwrapper can be found at http://virtualenvwrapper.readthedocs.org/en/latest/

Specific documentation on this feature can be found at http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html?highlight=add2virtualenv


回答 2

您可以创建一个.pth包含要搜索的目录的文件,并将其放置在site-packages目录中。例如:

cd $(python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())")
echo /some/library/path > some-library.pth

效果与添加/some/library/path到相同sys.path,并且保持在virtualenv设置本地。

You can create a .pth file that contains the directory to search for, and place it in the site-packages directory. E.g.:

cd $(python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())")
echo /some/library/path > some-library.pth

The effect is the same as adding /some/library/path to sys.path, and remain local to the virtualenv setup.


回答 3

  1. 初始化您的virtualenv
cd venv

source bin/activate
  1. 只需通过输入以下命令来设置或更改python路径:
export PYTHONPATH='/home/django/srmvenv/lib/python3.4'
  1. 用于检查python路径,请在python中输入:
   python

      \>\> import sys

      \>\> sys.path
  1. Initialize your virtualenv
cd venv

source bin/activate
  1. Just set or change your python path by entering command following:
export PYTHONPATH='/home/django/srmvenv/lib/python3.4'
  1. for checking python path enter in python:
   python

      \>\> import sys

      \>\> sys.path


回答 4

我修改了激活脚本以获取文件.virtualenvrc(如果文件存在于当前目录中)并PYTHONPATH在激活/停用时保存/恢复。

您可以在activate此处找到修补的脚本。。它是由virtualenv 1.11.6创建的激活脚本的直接替代。

然后我向我添加了类似的内容.virtualenvrc

export PYTHONPATH="${PYTHONPATH:+$PYTHONPATH:}/some/library/path"

I modified my activate script to source the file .virtualenvrc, if it exists in the current directory, and to save/restore PYTHONPATH on activate/deactivate.

You can find the patched activate script here.. It’s a drop-in replacement for the activate script created by virtualenv 1.11.6.

Then I added something like this to my .virtualenvrc:

export PYTHONPATH="${PYTHONPATH:+$PYTHONPATH:}/some/library/path"

回答 5

它已经在这里回答-> 我的虚拟环境(python)是否导致PYTHONPATH中断?

UNIX / Linux

将“ export PYTHONPATH = / usr / local / lib / python2.0”添加到〜/ .bashrc文件,并通过键入“ source〜/ .bashrc”或“。〜/ .bashrc”将其导出。

Windows XP

1)转到控制面板2)双击系统3)转到高级选项卡4)单击环境变量

在“系统变量”窗口中,检查是否有一个名为PYTHONPATH的变量。如果已经有了,请检查它是否指向正确的目录。如果还没有,请单击“新建”按钮并创建它。

密码

另外,您也可以在代码下方执行以下操作:-

import sys
sys.path.append("/home/me/mypy") 

It’s already answered here -> Is my virtual environment (python) causing my PYTHONPATH to break?

UNIX/LINUX

Add “export PYTHONPATH=/usr/local/lib/python2.0” this to ~/.bashrc file and source it by typing “source ~/.bashrc” OR “. ~/.bashrc”.

WINDOWS XP

1) Go to the Control panel 2) Double click System 3) Go to the Advanced tab 4) Click on Environment Variables

In the System Variables window, check if you have a variable named PYTHONPATH. If you have one already, check that it points to the right directories. If you don’t have one already, click the New button and create it.

PYTHON CODE

Alternatively, you can also do below your code:-

import sys
sys.path.append("/home/me/mypy") 

ImportError:没有名为“编码”的模块

问题:ImportError:没有名为“编码”的模块

我最近重新安装了ubuntu并升级到16.04,无法使用python:

$ python manage.py runserver
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
Aborted

在这一点上,python本身不起作用

$ python
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
Aborted

甚至这个建议也不再起作用:

unset PYTHONHOME
unset PYTHONPATH

每一次我用一种方式修复它,它都会再次出现。有几个答案有助于暂时修复它,但不是永久性的。我已经重新安装了python和python3几次。我可以从这里做什么?谢谢

I recently reinstalled ubuntu and did upgrade to 16.04 and cannot use python:

$ python manage.py runserver
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
Aborted

At this point, python itself doesn’t work

$ python
Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'
Aborted

Even this suggestion is no longer working:

unset PYTHONHOME
unset PYTHONPATH

Every every I fix it one way, it comes back again. Several answers help to fix it temporarily, but not for good. I’ve reinstalled python and python3 several times. What can I do from here? Thank you


回答 0

对于Python-3,请尝试删除虚拟环境文件。并重新设置它。

rm -rf venv
virtualenv -p /usr/bin/python3 venv/
source venv/bin/activate
pip install -r requirements.txt

https://wiki.ubuntu.com/XenialXerus/ReleaseNotes#Python_3 编辑

For Python-3 try removing virtual environment files. And resetting it up.

rm -rf venv
virtualenv -p /usr/bin/python3 venv/
source venv/bin/activate
pip install -r requirements.txt

https://wiki.ubuntu.com/XenialXerus/ReleaseNotes#Python_3 edit fo


回答 1

对于Windows10用户。

我在Windows10上使用python3.4。我安装了python3.5。我找不到PYTHONPATH,PYTHONHOME env变量。如果我在CMD控制台中命令python,它将继续使用python3.4。我删除了python3.4。每当我在CMD控制台中命令python时,它就会开始显示如下错误。

Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'

我搜寻以找出我的问题。解决方案很简单。安装python3.5时,可以自定义安装并在“高级选项”中选中“ 将Python添加到环境变量”

我只是在这里离开,以防有人遇到类似的问题来这里,以便他们不会浪费很多宝贵的时间来弄清楚。

For Windows10 User.

I was using python3.4 on Windows10. I installed python3.5. I couldn’t find PYTHONPATH, PYTHONHOME env variable. If I command python in CMD console, It kept using python3.4. I deleted python3.4. Whenever I command python in CMD console, it starts showing an error like below.

Fatal Python error: Py_Initialize: Unable to get the locale encoding
ImportError: No module named 'encodings'

I searched to figure out my problem. Solution was simple. When you install python3.5, you can custom install and check Add Python to environment variables in Advanced Options.

I just leave here for case that someone have similar issues visit here so that they don’t waste their precious time much to figure out.


回答 2

我在Windows7下也面临同样的问题。错误消息如下所示:

Fatal Python error: Py_Initialize: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

Current thread 0x000011f4 (most recent call first):

我已经安装了python 2.7(现在已卸载),并且在安装python 3.6时选中了“将Python添加到高级选项中的环境变量”。结果表明,环境变量“ PYTHONHOME ”和“ PYTHONPATH ”仍然是python2.7。

最后,我通过将“ PYTHONHOME ” 修改为python3.6安装路径并删除了变量“ PYTHONPATH ” 来解决了该问题。

I was facing the same problem under Windows7. The error message looks like that:

Fatal Python error: Py_Initialize: unable to load the file system codec
ModuleNotFoundError: No module named 'encodings'

Current thread 0x000011f4 (most recent call first):

I have installed python 2.7(uninstalled now), and I checked “Add Python to environment variables in Advanced Options” while installing python 3.6. It comes out that the Environment Variable “PYTHONHOME” and “PYTHONPATH” is still python2.7.

Finally I solved it by modify “PYTHONHOME” to python3.6 install path and remove variable “PYTHONPATH“.


回答 3

对于Windows7上的相同问题

如果您的环境变量/系统变量设置不正确,您将看到这样的错误:

Fatal Python error: Py_Initialize: unable to load the file system codec
ImportError: No module named 'encodings'

Current thread 0x00001db4 (most recent call first):

解决这个问题非常简单:

  1. 当您下载Python3.x版本并运行.exe文件时,它为您提供了一个自定义系统中要安装Python位置的选项。例如,我选择了以下位置:C:\ Program Files \ Python36

  2. 然后打开系统属性,然后转到“ 高级 ”选项卡(或者您可以简单地做到这一点:转到“开始”>“搜索” 环境变量 ”>单击“编辑系统环境变量”。)在“高级”选项卡下,查找单击“环境变量”,然后单击它。将会弹出另一个名为“环境变量”的窗口。

  3. 现在,确保您的用户变量具有“路径变量”中列出的正确的Python路径。在这里的示例中,您应该看到C:\ Program Files \ Python36。如果在此处找不到它,则通过选择“路径变量”字段并单击“编辑”来添加它。

  4. 最后一步是在同一窗口中的系统变量下仔细检查PYTHONHOMEPYTHONPATH字段。您应该看到与上述相同的路径。如果没有也添加它。

然后单击“确定”并返回到CMD终端,然后尝试检查python。现在应解决此问题。它为我工作。

For the same issue on Windows7

You will see an error like this if your environment variables/ system variables are incorrectly set:

Fatal Python error: Py_Initialize: unable to load the file system codec
ImportError: No module named 'encodings'

Current thread 0x00001db4 (most recent call first):

Fixing this is really simple:

  1. When you download Python3.x version, and run the .exe file, it gives you an option to customize where in your system you want to install Python. For example, I chose this location: C:\Program Files\Python36

  2. Then open system properties and go to “Advanced” tab (Or you can simply do this: Go to Start > Search for “environment variables” > Click on “Edit the system environment variables”.) Under the “Advanced” tab, look for “Environment Variables” and click it. Another window with name “Environment Variables” will pop up.

  3. Now make sure your user variables have the correct Python path listed in “Path Variable”. In my example here, you should see C:\Program Files\Python36. If you do not find it there, add it, by selecting Path Variable field and clicking Edit.

  4. Last step is to double-check PYTHONHOME and PYTHONPATH fields under System Variables in the same window. You should see the same path as described above. If not add it there too.

Then click OK and go back to CMD terminal, and try checking for python. The issue should now be resolved. It worked for me.


回答 4

在迁移到Ubuntu 17.10的过程中出现了此错误,这解决了问题:

sudo dpkg-reconfigure python3

也许您必须关闭会话并重新连接。

I had this error during migration to Ubuntu 17.10, and this solved the problem :

sudo dpkg-reconfigure python3

Maybe you will have to close your session and reconnect.


回答 5

查看/lib/python3.5,您将看到指向python库的断开链接。将其重新创建到工作目录。

下一个错误-

./script/bin/pip3
Failed to import the site module
Traceback (most recent call last):
  File "/home/script/script/lib/python3.5/site.py", line 703, in <module>
    main()
  File "/home/script/script/lib/python3.5/site.py", line 683, in main
    paths_in_sys = addsitepackages(paths_in_sys)
  File "/home/script/script/lib/python3.5/site.py", line 282, in addsitepackages
    addsitedir(sitedir, known_paths)
  File "/home/script/script/lib/python3.5/site.py", line 204, in addsitedir
    addpackage(sitedir, name, known_paths)
  File "/home/script/script/lib/python3.5/site.py", line 173, in addpackage
    exec(line)
  File "<string>", line 1, in <module>
  File "/home/script/script/lib/python3.5/types.py", line 166, in <module>
    import functools as _functools
  File "/home/script/script/lib/python3.5/functools.py", line 23, in <module>
    from weakref import WeakKeyDictionary
  File "/home/script/script/lib/python3.5/weakref.py", line 12, in <module>
    from _weakref import (
ImportError: cannot import name '_remove_dead_weakref'

像这样固定-https: //askubuntu.com/questions/907035/importerror-cannot-import-name-remove-dead-weakref

cd my-virtualenv-directory
virtualenv . --system-site-packages

Look at /lib/python3.5 and you will see broken links to python libraries. Recreate it to working directory.

Next error –

./script/bin/pip3
Failed to import the site module
Traceback (most recent call last):
  File "/home/script/script/lib/python3.5/site.py", line 703, in <module>
    main()
  File "/home/script/script/lib/python3.5/site.py", line 683, in main
    paths_in_sys = addsitepackages(paths_in_sys)
  File "/home/script/script/lib/python3.5/site.py", line 282, in addsitepackages
    addsitedir(sitedir, known_paths)
  File "/home/script/script/lib/python3.5/site.py", line 204, in addsitedir
    addpackage(sitedir, name, known_paths)
  File "/home/script/script/lib/python3.5/site.py", line 173, in addpackage
    exec(line)
  File "<string>", line 1, in <module>
  File "/home/script/script/lib/python3.5/types.py", line 166, in <module>
    import functools as _functools
  File "/home/script/script/lib/python3.5/functools.py", line 23, in <module>
    from weakref import WeakKeyDictionary
  File "/home/script/script/lib/python3.5/weakref.py", line 12, in <module>
    from _weakref import (
ImportError: cannot import name '_remove_dead_weakref'

fixed like this – https://askubuntu.com/questions/907035/importerror-cannot-import-name-remove-dead-weakref

cd my-virtualenv-directory
virtualenv . --system-site-packages

回答 6

更新到macOS Catalina后,我遇到了此问题“ ModuleNotFoundError:没有名为’encodings的模块”。

我在系统中安装了多个版本的Python。

从macOS系统中删除所有python版本(2.7和3.7.4)并重新安装最新的python 3.8对我来说很有效。

要从macOS中删除python,我已遵循此处的说明如何在Mac OS X 10.6.4上卸载Python 2.7?

上面的链接适用于python 2.7,但是您也可以将其用于3.7。

I was facing this issue “ModuleNotFoundError: No module named ‘encodings” after updating to macOS Catalina.

I was having multiple versions of Python installed in my system.

Removing all the python versions(2.7 and 3.7.4) from macOS system and reinstalling the latest python 3.8 worked for me.

To remove a python from macOS, I’ve followed the instructions from here How to uninstall Python 2.7 on a Mac OS X 10.6.4?

The above link is for python 2.7 and but you can use the same for 3.7 also.


回答 7

我有一个类似的问题。我在计算机上同时安装了anaconda和python,而我的python依赖项则来自Anaconda目录。当我卸载Anaconda时,此错误开始弹出。我加了,PYTHONPATH但还是没去。我检查了python -version一下,发现它仍在沿用Python之路。我不得不手动删除Anaconda3目录,然后python开始从接收依赖PYTHONPATH
问题已解决!

I had a similar issue. I had both anaconda and python installed on my computer and my python dependencies were from the Anaconda directory. When I uninstalled Anaconda, this error started popping. I added PYTHONPATH but it still didn’t go. I checked with python -version and go to know that it was still taking the anaconda path. I had to manually delete Anaconda3 directory and after that python started taking dependencies from PYTHONPATH.
Issue Solved!


回答 8

使用时将我的mac更新到macOS Catalina时遇到了相同的问题pipenv。Pipenv virtualenv为您创建并管理一个,因此@ Anoop-Malav的早期建议是相同的,只是使用pipenv根据当前目录删除虚拟环境并重置它:

pipenv --rm
pipenv shell  # recreate a virtual env with your current Pipfile

Had the same problem when updating my mac to macOS Catalina, while using pipenv. Pipenv creates and manages a virtualenv for you, so the earlier suggestion from @Anoop-Malav is the same, just using pipenv to remove the virtual environment based on the current dir and reset it:

pipenv --rm
pipenv shell  # recreate a virtual env with your current Pipfile

回答 9

在我的情况下,只需更改anaconda文件夹的权限即可:

sudo chmod -R u=rwx,g=rx,o=rx /path/to/anaconda   

In my case just changing the permissions of anaconda folder worked:

sudo chmod -R u=rwx,g=rx,o=rx /path/to/anaconda   

回答 10

因为这是google的第一个结果,所以我只想向其他有监狱问题的人添加以下信息:

Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f079b16d740 (most recent call first):
Aborted (core dumped)

尝试将python导入监狱时,您都需要将依赖项和/usr/lib/pythonX.Y链接到[JAIL] / usr / lib /。希望这可以帮助。

Because this is the first result in google I just want to add the following information for anybody else having problems with jails:

Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f079b16d740 (most recent call first):
Aborted (core dumped)

When attempting to import python into your jail you both need to link the dependencies and /usr/lib/pythonX.Y to [JAIL]/usr/lib/. Hope this helps.


回答 11

只需转到File-> Settings->在Project选项卡下选择Project Interpreter->单击小齿轮图标-> Add-> System Interpreter->在下拉菜单中选择所需的python版本

这似乎对我有用

Just go to File -> Settings -> select Project Interpreter under Project tab -> click on the small gear icon -> Add -> System Interpreter -> select the python version you want in the drop down menu

this seemed to work for me


回答 12

我也可以解决这个问题。PYTHONPATH和PYTHONHOME是原因。

在终端上运行

   touch ~/.bash_profile
   open ~/.bash_profile

然后删除此文件的所有无用部分,然后保存。我不知道这样做是多么推荐!

I could also fix this. PYTHONPATH and PYTHONHOME were in cause.

run this in a terminal

   touch ~/.bash_profile
   open ~/.bash_profile

and then delete all useless parts of this file, and save. I do not know how recommended it is to do that !


‘python setup.py install’和’pip install’之间的区别

问题:’python setup.py install’和’pip install’之间的区别

我有一个要从tar文件安装到python virtualenv中的外部软件包。安装软件包的最佳方法是什么?

我发现了两种方法可以做到这一点:

  1. 提取tar文件,然后python setup.py install在提取的目录中运行。
  2. pip install packagename.tar.gz来自https://pip.pypa.io/en/stable/reference/pip_install/#examples中的示例7

这两种方式在做上是否有区别。

I have an external package I want to install into my python virtualenv from a tar file. What is the best way to install the package?

I’ve discovered 2 ways that can do it:

  1. Extract the tar file, then run python setup.py install inside of the extracted directory.
  2. pip install packagename.tar.gz from example # 7 in https://pip.pypa.io/en/stable/reference/pip_install/#examples

Is if there is any difference doing them in these 2 ways.


回答 0

从表面上看,都做同样的事情:无论是做python setup.py install还是pip install <PACKAGE-NAME>会安装Python包的你,有大惊小怪的最低金额。

但是,使用pip具有一些其他优点,使其更易于使用。

  • pip将自动为您下载软件包的所有依赖项。相反,如果使用setup.py,则通常必须手动搜索并下载依赖项,这很乏味并且会令人沮丧。
  • pip跟踪各种元数据,使您可以使用一个命令轻松卸载和更新软件包:pip uninstall <PACKAGE-NAME>pip install --upgrade <PACKAGE-NAME>。相反,如果您使用setup.py,则要想摆脱它,必须手动手动删除和维护该软件包,这可能容易出错。
  • 您不再需要手动下载文件。如果您使用setup.py,则必须访问图书馆的网站,弄清楚从哪里下载,提取文件,运行setup.py…相比之下,pip会自动搜索Python软件包索引(PyPi)来查看该软件包是否存在,以及会自动为您下载,解压缩并安装该软件包。除了少数exceptions,几乎所有真正有用的Python库都可以在PyPi上找到。
  • pip可让您轻松安装轮子,这是Python发行版的新标准。有关轮子的更多信息
  • pip提供了与using良好集成的其他好处virtualenv,该程序使您可以运行多个项目,这些项目需要计算机上具有冲突的库和Python版本。更多信息
  • pip默认情况下与Python 2.x系列的Python 2.7.9及Python 3.x系列的Python 3.4.0及更高版本捆绑在一起,从而更加易于使用。

因此,基本上,使用点子。它仅提供对的改进python setup.py install


如果您使用的是旧版本的Python,无法升级且未安装pip,则可以在以下链接中找到有关安装pip的更多信息:

pip本身并不需要教程。90%的时间,您真正需要的唯一命令是pip install <PACKAGE-NAME>。就是说,如果您想了解更多有关pip的功能的详细信息,请参阅:

通常也建议同时使用pip和virtualenv。如果您是Python的初学者,我个人认为最好只使用pip并在全球范围内安装软件包,但最终我还是认为在处理更严重的项目时,您应该过渡到使用virtualenv。

如果您想了解有关一起使用pip和virtualenv的更多信息,请参见:

On the surface, both do the same thing: doing either python setup.py install or pip install <PACKAGE-NAME> will install your python package for you, with a minimum amount of fuss.

However, using pip offers some additional advantages that make it much nicer to use.

  • pip will automatically download all dependencies for a package for you. In contrast, if you use setup.py, you often have to manually search out and download dependencies, which is tedious and can become frustrating.
  • pip keeps track of various metadata that lets you easily uninstall and update packages with a single command: pip uninstall <PACKAGE-NAME> and pip install --upgrade <PACKAGE-NAME>. In contrast, if you install a package using setup.py, you have to manually delete and maintain a package by hand if you want to get rid of it, which could be potentially error-prone.
  • You no longer have to manually download your files. If you use setup.py, you have to visit the library’s website, figure out where to download it, extract the file, run setup.py… In contrast, pip will automatically search the Python Package Index (PyPi) to see if the package exists there, and will automatically download, extract, and install the package for you. With a few exceptions, almost every single genuinely useful Python library can be found on PyPi.
  • pip will let you easily install wheels, which is the new standard of Python distribution. More info about wheels.
  • pip offers additional benefits that integrate well with using virtualenv, which is a program that lets you run multiple projects that require conflicting libraries and Python versions on your computer. More info.
  • pip is bundled by default with Python as of Python 2.7.9 on the Python 2.x series, and as of Python 3.4.0 on the Python 3.x series, making it even easier to use.

So basically, use pip. It only offers improvements over using python setup.py install.


If you’re using an older version of Python, can’t upgrade, and don’t have pip installed, you can find more information about installing pip at the following links:

pip, by itself, doesn’t really require a tutorial. 90% of the time, the only command you really need is pip install <PACKAGE-NAME>. That said, if you’re interested in learning more about the details of what exactly you can do with pip, see:

It is also commonly recommended that you use pip and virtualenv together. If you’re a beginner to Python, I personally think it’d be fine to start of with just using pip and install packages globally, but eventually I do think you should transition to using virtualenv as you tackle more serious projects.

If you’d like to learn more about using pip and virtualenv together, see:


回答 1

python setup.py install与make install类似:这是将文件编译和复制到目标目录的有限方式。这并不意味着它是在系统上真正安装软件的最佳方法。

pip是一个程序包管理器,可以安装,升级,列出和卸载程序包,例如熟悉的程序包管理器,包括:dpkg, apt, yum, urpmi, ports等。它可以在内运行python setup.py install,但具有特定的选项来控制最终安装的方式和位置。

总结:使用pip

python setup.py install is the analog of make install: it’s a limited way to compile and copy files to destination directories. This doesn’t mean that it’s the best way to really install software on your system.

pip is a package manager, which can install, upgrade, list and uninstall packages, like familiar package managers including: dpkg, apt, yum, urpmi, ports etc. Under the hood, it will run python setup.py install, but with specific options to control how and where things end up installed.

In summary: use pip.


回答 2

问题是关于安装包含python软件包而不是NOT 的本地tarball的首选方法关于将软件包上传到索引服务(如PyPi)的好处。

至少我知道一些软件发行商不会将其软件包上传到PyPi,而是要求开发人员从其网站下载软件包并进行安装。

python setup.py安装

这可以工作,但不建议这样做。无需解压缩tarball文件并进入其中以运行setup.py文件。

点安装../path/to/packagename.tar.gz

这是设计和首选的方式。简洁并与PyPi样式的包对齐。

有关更多信息,请pip install参见:https//pip.readthedocs.io/en/stable/reference/pip_install/

The question is about the preferred method to install a local tarball containing a python package, NOT about the advantage of uploading package to an indexing service like PyPi.

As lest I know some software distributor does not upload their package to PyPi, instead asking developers to download package from their website and install.

python setup.py install

This can work but not recommended. It’s not necessary to unwrap the tarball file and go into it to run setup.py file.

pip install ../path/to/packagename.tar.gz

This is the way designed and preferred. Concise and align with PyPi-style packages.

More information about pip install can be found here: https://pip.readthedocs.io/en/stable/reference/pip_install/