从另一个Python-ins导入的模块

2024-09-30 22:17:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我在WindowsServer2012上运行了多个Python安装程序。我也许能找到一个办法来解决这个问题,但我很好奇到底发生了什么。我对彻底改变安装方式持谨慎态度,以防破坏其他人安排的Python任务,而我可能不知道。在

(下面所有的代码框都是PowerShell)。在

PS C:\> C:\Python34\Scripts\pip.exe list
jdcal (1.0)
pip (7.1.2)
setuptools (12.0.5)
virtualenv (13.1.2)

尽管这个python3.4安装没有安装Django,但它似乎是从python33x86安装中获取的版本。这正常吗?在

^{pr2}$

我已经创建了一个基于python3.4的pythonvirtualenv,并在其中安装了django1.8.4。执行“pip list”确认它已安装正确:-在

PS C:\> D:\PyVirtualEnvs\example_py34\Scripts\activate.bat
PS C:\> D:\PyVirtualEnvs\example_py34\Scripts\pip.exe list | Select-String "Django "
Django (1.8.4)

但是,当我在该virtualenv中导入时,我得到了Django版本1.6.5:

PS C:\> D:\PyVirtualEnvs\example_py34\Scripts\python.exe -c "import django; print(django.get_version())"
1.6.5

这是virtualenv中的bug还是我遗漏了什么?在

编辑:是否与this question有关?在

编辑2:使用pyvenv时也会发生同样的事情,正如火腿三明治所建议的那样。在


Tags: pipdjango版本编辑virtualenvexamplescriptsexe
3条回答

如果从PowerShell(批处理文件)运行cmd.exeshell脚本,PowerShell将生成cmd.exe的实例来运行脚本(批处理文件)。如果批处理文件设置环境变量,则它们只存在于生成的cmd.exe实例中。在这种情况下,调用PowerShell的过程结束(在这种情况下,调用PowerShell的过程终止一次)。这是故意的。在

如果要传播环境变量,可以在PowerShell中使用以下Invoke-CmdScript函数:

function Invoke-CmdScript {
  param(
    [String] $scriptName
  )
  $cmdLine = """$scriptName"" $args & set"
  & $Env:SystemRoot\system32\cmd.exe /c $cmdLine |
  Select-String '^([^=]*)=(.*)$' | ForEach-Object {
    $varName = $_.Matches[0].Groups[1].Value
    $varValue = $_.Matches[0].Groups[2].Value
    Set-Item Env:$varName $varValue
  }
}

以下文章提供了有关此方面的更多信息:

Windows IT Pro: Take Charge of Environment Variables in PowerShell

在您的情况下,您将运行:

^{pr2}$

这将生成activate.bat并传播环境变量更改。在

我发现了这种行为的原因。PYTHONPATH环境变量被设置为在计算机上不寻常的位置安装的Python。在

根据the documentation,当当前目录中找不到模块时,PYTHONPATH将用作导入位置。在

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • the directory containing the input script (or the current directory).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • the installation-dependent default.

由于某些原因,PYTHONPATH不是由activate/deactivate脚本设置/取消设置的。它确实设置了PYTHONHOME,但这似乎不影响进口。这感觉像是virtualenv和pyvenv中的bug(我都试过了)。在

原来的激活.bat脚本更改“set”变量,这不会影响$环境:Python。激活.ps1尝试将原始PYTHONPATH保存在变量中,将其设置为虚拟环境目录,然后在停用时恢复原始PYTHONPATH。这两种方法都不起作用了,可能是因为Powershell或Python更新。在

我们的解决方案是修改activate和deactivate脚本(PoSh或bat),以便在两个硬编码值之间切换PYTHONPATH。在

我唯一觉得奇怪的是你在跑步

D:\PyVirtualEnvs\example_py34\Scripts\activate.bat

在powershell中,当激活.ps1. 我不知道这是否有兼容性问题。在

相关问题 更多 >