标签归档:pythonpath

将目录添加到sys.path / PYTHONPATH

问题:将目录添加到sys.path / PYTHONPATH

我正在尝试从特定目录导入模块。

问题是,如果我使用sys.path.append(mod_directory)追加路径然后打开python解释器,该目录mod_directory将添加到列表sys.path的末尾。如果我PYTHONPATH在打开python解释器之前导出变量,则目录将添加到列表的开头。在后一种情况下,我可以导入模块,但是在前一种情况下,我不能。

有人可以解释为什么会发生这种情况,并给我一个 python脚本中将其添加mod_directory到开始的解决方案吗?

I am trying to import a module from a particular directory.

The problem is that if I use sys.path.append(mod_directory) to append the path and then open the python interpreter, the directory mod_directory gets added to the end of the list sys.path. If I export the PYTHONPATH variable before opening the python interpreter, the directory gets added to the start of the list. In the latter case I can import the module but in the former, I cannot.

Can somebody explain why this is happening and give me a solution to add the mod_directory to the start, inside a python script ?


回答 0

如文档所述,这正在工作。PYTHONPATH文件中指定的所有路径通常在工作目录之后但在标准解释器提供的路径之前记录。 sys.path.append()追加到现有路径。看到这里这里。如果要让特定目录优先出现,只需将其插入sys.path的开头即可:

import sys
sys.path.insert(0,'/path/to/mod_directory')

就是说,通常有比直接使用PYTHONPATH或操纵更好的方法来管理进口sys.path。例如,请参阅此问题的答案。

This is working as documented. Any paths specified in PYTHONPATH are documented as normally coming after the working directory but before the standard interpreter-supplied paths. sys.path.append() appends to the existing path. See here and here. If you want a particular directory to come first, simply insert it at the head of sys.path:

import sys
sys.path.insert(0,'/path/to/mod_directory')

That said, there are usually better ways to manage imports than either using PYTHONPATH or manipulating sys.path directly. See, for example, the answers to this question.


回答 1

您可以使用:

import os
path = 'the path you want'
os.environ['PATH'] += ':'+path

You could use:

import os
path = 'the path you want'
os.environ['PATH'] += ':'+path

回答 2

对于我来说,我需要了解我的python路径。我可以将它的路径添加到该文件 /home/xy/.bashrc由add

export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH

到我的/home/xy/.bashrc文件。

但是当我使用pycharm时,路径仍然不在。

因此,我可以PYTHONPATH通过运行->编辑配置将路径添加到变量。

As to me, i need to caffe to my python path. I can add it’s path to the file /home/xy/.bashrc by add

export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH.

to my /home/xy/.bashrc file.

But when I use pycharm, the path is still not in.

So I can add path to PYTHONPATH variable, by run -> edit Configuration.


回答 3

临时更改目录可以很好地导入:

cwd = os.getcwd()
os.chdir(<module_path>)
import <module>
os.chdir(cwd)

Temporarily changing dirs works well for importing:

cwd = os.getcwd()
os.chdir(<module_path>)
import <module>
os.chdir(cwd)

回答 4

在Windows下从Powershell运行Python脚本时,这应该可以工作:

$pathToSourceRoot = "C:/Users/Steve/YourCode"
$env:PYTHONPATH = "$($pathToSourceRoot);$($pathToSourceRoot)/subdirs_if_required"

# Now run the actual script
python your_script.py

When running a Python script from Powershell under Windows, this should work:

$pathToSourceRoot = "C:/Users/Steve/YourCode"
$env:PYTHONPATH = "$($pathToSourceRoot);$($pathToSourceRoot)/subdirs_if_required"

# Now run the actual script
python your_script.py

PyLint“无法导入”错误-如何设置PYTHONPATH?

问题:PyLint“无法导入”错误-如何设置PYTHONPATH?

我正在Windows的Wing IDE中运行PyLint。我的项目中有一个子目录(程序包),在程序包中,我从顶层(即)导入模块。

__init__.py
myapp.py
one.py
subdir\
    __init__.py
    two.py

two.py我的内部import one,这在运行时效果很好,因为顶层目录(从中myapp.py运行)位于Python路径中。但是,当我在two.py上运行PyLint时,出现了一个错误:

F0401: Unable to import 'one'

我该如何解决?

I’m running PyLint from inside Wing IDE on Windows. I have a sub-directory (package) in my project and inside the package I import a module from the top level, ie.

__init__.py
myapp.py
one.py
subdir\
    __init__.py
    two.py

Inside two.py I have import one and this works fine at runtime, because the top-level directory (from which myapp.py is run) is in the Python path. However, when I run PyLint on two.py it gives me an error:

F0401: Unable to import 'one'

How do I fix this?


回答 0

我知道有两个选择。

一,更改PYTHONPATH环境变量,使其包含模块上方的目录。

或者,编辑~/.pylintrc以包括模块上方的目录,如下所示:

[MASTER]
init-hook='import sys; sys.path.append("/path/to/root")'

(或者在其他版本的pylint中,init-hook要求您将[General]更改为[MASTER])

这两个选项都应该起作用。

希望有帮助。

There are two options I’m aware of.

One, change the PYTHONPATH environment variable to include the directory above your module.

Alternatively, edit ~/.pylintrc to include the directory above your module, like this:

[MASTER]
init-hook='import sys; sys.path.append("/path/to/root")'

(Or in other version of pylint, the init-hook requires you to change [General] to [MASTER])

Both of these options ought to work.

Hope that helps.


回答 1

更改路径的解决方案init-hook很好,但是我不喜欢必须在此处添加绝对路径的事实,因此,我无法在项目开发人员之间共享此pylintrc文件。这种使用相对路径指向pylintrc文件的解决方案对我来说效果更好:

[MASTER]
init-hook="from pylint.config import find_pylintrc; import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"

请注意,pylint.config.PYLINTRC该值也存在,并且具有与相同的值find_pylintrc()

The solution to alter path in init-hook is good, but I dislike the fact that I had to add absolute path there, as result I can not share this pylintrc file among the developers of the project. This solution using relative path to pylintrc file works better for me:

[MASTER]
init-hook="from pylint.config import find_pylintrc; import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"

Note that pylint.config.PYLINTRC also exists and has the same value as find_pylintrc().


回答 2

1)sys.path是一个列表。

2)问题有时是sys.path不是您的virtualenv.path,并且您想在virtualenv中使用pylint

3)像这样说,使用init-hook(注意’和’pylint的解析是严格的)

[Master]
init-hook='sys.path = ["/path/myapps/bin/", "/path/to/myapps/lib/python3.3/site-packages/", ... many paths here])'

要么

[Master]
init-hook='sys.path = list(); sys.path.append("/path/to/foo")'

..和

pylint --rcfile /path/to/pylintrc /path/to/module.py

1) sys.path is a list.

2) The problem is sometimes the sys.path is not your virtualenv.path and you want to use pylint in your virtualenv

3) So like said, use init-hook (pay attention in ‘ and ” the parse of pylint is strict)

[Master]
init-hook='sys.path = ["/path/myapps/bin/", "/path/to/myapps/lib/python3.3/site-packages/", ... many paths here])'

or

[Master]
init-hook='sys.path = list(); sys.path.append("/path/to/foo")'

.. and

pylint --rcfile /path/to/pylintrc /path/to/module.py

回答 3

可以通过在venv下配置pylint路径来解决该问题:$ cat .vscode / settings.json

{
    "python.pythonPath": "venv/bin/python",
    "python.linting.pylintPath": "venv/bin/pylint"
}

The problem can be solved by configuring pylint path under venv: $ cat .vscode/settings.json

{
    "python.pythonPath": "venv/bin/python",
    "python.linting.pylintPath": "venv/bin/pylint"
}

回答 4

您是否__init__.py在两个目录中都有一个空文件来让python知道dirs是模块?

当您不在文件夹中运行时(例如,虽然不是我使用过的pylint),其基本轮廓是:

topdir\
  __init__.py
  functions_etc.py
  subdir\
    __init__.py
    other_functions.py

这是怎样的Python解释器知道不参考当前目录中的模块,因此,如果pylint的是从自身的绝对路径运行它就能访问functions_etc.pytopdir.functions_etctopdir.subdir.other_functions,只要topdir是对的PYTHONPATH

更新:如果问题不在于__init__.py文件,也许只是尝试将模块复制或移动到c:\Python26\Lib\site-packages-这是放置其他软件包的常见位置,并且肯定会在pythonpath上。如果您知道如何执行Windows符号链接或等效链接(我不知道!),则可以这样做。这里还有更多选项:http://docs.python.org/install/index.html,包括在开发代码的用户级目录后附加sys.path的选项,但实际上,我通常只是象征性地链接我将本地开发目录复制到站点软件包-将其复制具有相同的效果。

Do you have an empty __init__.py file in both directories to let python know that the dirs are modules?

The basic outline when you are not running from within the folder (ie maybe from pylint’s, though I haven’t used that) is:

topdir\
  __init__.py
  functions_etc.py
  subdir\
    __init__.py
    other_functions.py

This is how the python interpreter is aware of the module without reference to the current directory, so if pylint is running from its own absolute path it will be able to access functions_etc.py as topdir.functions_etc or topdir.subdir.other_functions, provided topdir is on the PYTHONPATH.

UPDATE: If the problem is not the __init__.py file, maybe just try copying or moving your module to c:\Python26\Lib\site-packages — that is a common place to put additional packages, and will definitely be on your pythonpath. If you know how to do Windows symbolic links or the equivalent (I don’t!), you could do that instead. There are many more options here: http://docs.python.org/install/index.html, including the option of appending sys.path with the user-level directory of your development code, but in practice I usually just symbolically link my local development dir to site-packages – copying it over has the same effect.


回答 5

我在此页面上找到的关于此问题的一般答案请不要打开,网站显示错误

创建.pylintrc并添加

[MASTER]
init-hook="from pylint.config import find_pylintrc;
import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"

general answer for this question I found on this page PLEASE NOT OPEN, SITE IS BUGED

create .pylintrc and add

[MASTER]
init-hook="from pylint.config import find_pylintrc;
import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"

回答 6

我不知道它如何与WingIDE一起使用,但是对于将PyLint与Geany一起使用,我将外部命令设置为:

PYTHONPATH=${PYTHONPATH}:$(dirname %d) pylint --output-format=parseable --reports=n "%f"

其中%f是文件名,%d是路径。可能对某人有用:)

I don’t know how it works with WingIDE, but for using PyLint with Geany, I set my external command to:

PYTHONPATH=${PYTHONPATH}:$(dirname %d) pylint --output-format=parseable --reports=n "%f"

where %f is the filename, and %d is the path. Might be useful for someone :)


回答 7

我必须更新系统PYTHONPATH变量以添加我的App Engine路径。就我而言,我只需要编辑~/.bashrc文件并添加以下行:

export PYTHONPATH=$PYTHONPATH:/path/to/google_appengine_folder

实际上,我尝试设置第init-hook一个,但这不能在我的代码库中始终解决此问题(不确定原因)。一旦将其添加到系统路径中(一般来说可能是一个好主意),我的问题就消失了。

I had to update the system PYTHONPATH variable to add my App Engine path. In my case I just had to edit my ~/.bashrc file and add the following line:

export PYTHONPATH=$PYTHONPATH:/path/to/google_appengine_folder

In fact, I tried setting the init-hook first but this did not resolve the issue consistently across my code base (not sure why). Once I added it to the system path (probably a good idea in general) my issues went away.


回答 8

我刚刚发现的一种解决方法是实际上只对整个软件包运行PyLint,而不是对单个文件运行。不知何故,它设法找到了导入的模块。

One workaround that I only just discovered is to actually just run PyLint for the entire package, rather than a single file. Somehow, it manages to find imported module then.


回答 9

尝试

if __name__ == '__main__':
    from [whatever the name of your package is] import one
else:
    import one

请注意,在Python 3中,else子句中该部分的语法为

from .. import one

再三考虑,这可能无法解决您的特定问题。我误解了这个问题,并认为two.py已作为主要模块运行,但事实并非如此。考虑到Python 2.6(不absolute_import从导入__future__)和Python 3.x处理导入的方式的差异,我认为对于Python 2.6无需这样做。

不过,如果最终您确实切换到Python 3,并计划将模块既用作包模块又用作包内的独立脚本,那么最好保留以下内容:

if __name__ == '__main__':
    from [whatever the name of your package is] import one   # assuming the package is in the current working directory or a subdirectory of PYTHONPATH
else:
    from .. import one

心里。

编辑:现在为您的实际问题提供可能的解决方案。从包含one模块的目录中运行PyLint (也许通过命令行),或者在运行PyLint时将以下代码放在某个位置:

import os

olddir = os.getcwd()
os.chdir([path_of_directory_containing_module_one])
import one
os.chdir(olddir)

基本上,作为摆弄PYTHONPATH的替代方法,只需确保当前工作目录是one.py执行导入时包含的目录。

(查看Brian的答案,您可能会将先前的代码分配给init_hook,但是如果您打算这样做,则可以简单地对其进行附加sys.path操作,这比我的解决方案要优雅得多。)

Try

if __name__ == '__main__':
    from [whatever the name of your package is] import one
else:
    import one

Note that in Python 3, the syntax for the part in the else clause would be

from .. import one

On second thought, this probably won’t fix your specific problem. I misunderstood the question and thought that two.py was being run as the main module, but that is not the case. And considering the differences in the way Python 2.6 (without importing absolute_import from __future__) and Python 3.x handle imports, you wouldn’t need to do this for Python 2.6 anyway, I don’t think.

Still, if you do eventually switch to Python 3 and plan on using a module as both a package module and as a standalone script inside the package, it may be a good idea to keep something like

if __name__ == '__main__':
    from [whatever the name of your package is] import one   # assuming the package is in the current working directory or a subdirectory of PYTHONPATH
else:
    from .. import one

in mind.

EDIT: And now for a possible solution to your actual problem. Either run PyLint from the directory containing your one module (via the command line, perhaps), or put the following code somewhere when running PyLint:

import os

olddir = os.getcwd()
os.chdir([path_of_directory_containing_module_one])
import one
os.chdir(olddir)

Basically, as an alternative to fiddling with PYTHONPATH, just make sure the current working directory is the directory containing one.py when you do the import.

(Looking at Brian’s answer, you could probably assign the previous code to init_hook, but if you’re going to do that then you could simply do the appending to sys.path that he does, which is slightly more elegant than my solution.)


回答 10

关键是在sys.path不考虑env变量的情况下将项目目录添加到其中。

对于使用VSCode的人,如果您的项目有基本目录,这是一种单线解决方案:

[MASTER]
init-hook='base_dir="my_spider"; import sys,os,re; _re=re.search(r".+\/" + base_dir, os.getcwd()); project_dir = _re.group() if _re else os.path.join(os.getcwd(), base_dir); sys.path.append(project_dir)'

让我解释一下:

  • re.search(r".+\/" + base_dir, os.getcwd()).group():根据编辑文件查找基本目录

  • os.path.join(os.getcwd(), base_dir):添加cwdsys.path满足命令行环境


仅供参考,这是我的.pylintrc:

https://gist.github.com/chuyik/f0ffc41a6948b6c87c7160151ffe8c2f

The key is to add your project directory to sys.path without considering about the env variable.

For someone who use VSCode, here’s a one-line solution for you if there’s a base directory of your project:

[MASTER]
init-hook='base_dir="my_spider"; import sys,os,re; _re=re.search(r".+\/" + base_dir, os.getcwd()); project_dir = _re.group() if _re else os.path.join(os.getcwd(), base_dir); sys.path.append(project_dir)'

Let me explain it a little bit:

  • re.search(r".+\/" + base_dir, os.getcwd()).group(): find base directory according to the editing file

  • os.path.join(os.getcwd(), base_dir): add cwd to sys.path to meet command line environment


FYI, here’s my .pylintrc:

https://gist.github.com/chuyik/f0ffc41a6948b6c87c7160151ffe8c2f


回答 11

我遇到了同样的问题,并通过在virtualenv中安装pylint,然后将.pylintrc文件添加到我的项目目录中并在文件中添加以下内容来修复了该问题:

[Master]
init-hook='sys.path = list(); sys.path.append("./Lib/site-packages/")'

I had this same issue and fixed it by installing pylint in my virtualenv and then adding a .pylintrc file to my project directory with the following in the file:

[Master]
init-hook='sys.path = list(); sys.path.append("./Lib/site-packages/")'

回答 12

也许通过在PYTHONPATH内手动附加目录?

sys.path.append(dirname)

Maybe by manually appending the dir inside the PYTHONPATH?

sys.path.append(dirname)

回答 13

我遇到了同样的问题,因为我找不到答案,所以我希望这可以帮助任何有类似问题的人。

我用飞配epylint。基本上我所做的就是添加一个dired-mode-hook,以检查dired目录是否为python软件包目录。如果是,我将其添加到PYTHONPATH。就我而言,如果目录包含名为“ setup.py”的文件,则我认为该目录是python软件包。

;;;;;;;;;;;;;;;;;
;; PYTHON PATH ;;
;;;;;;;;;;;;;;;;;

(defun python-expand-path ()
  "Append a directory to the PYTHONPATH."
  (interactive
   (let ((string (read-directory-name 
          "Python package directory: " 
          nil 
          'my-history)))
     (setenv "PYTHONPATH" (concat (expand-file-name string)
                  (getenv ":PYTHONPATH"))))))

(defun pythonpath-dired-mode-hook ()
  (let ((setup_py (concat default-directory "setup.py"))
    (directory (expand-file-name default-directory)))
    ;;   (if (file-exists-p setup_py)
    (if (is-python-package-directory directory)
    (let ((pythonpath (concat (getenv "PYTHONPATH") ":" 
                  (expand-file-name directory))))
      (setenv "PYTHONPATH" pythonpath)
      (message (concat "PYTHONPATH=" (getenv "PYTHONPATH")))))))

(defun is-python-package-directory (directory)
  (let ((setup_py (concat directory "setup.py")))
    (file-exists-p setup_py)))

(add-hook 'dired-mode-hook 'pythonpath-dired-mode-hook)

希望这可以帮助。

I had the same problem and since i could not find a answer I hope this can help anyone with a similar problem.

I use flymake with epylint. Basically what i did was add a dired-mode-hook that check if the dired directory is a python package directory. If it is I add it to the PYTHONPATH. In my case I consider a directory to be a python package if it contains a file named “setup.py”.

;;;;;;;;;;;;;;;;;
;; PYTHON PATH ;;
;;;;;;;;;;;;;;;;;

(defun python-expand-path ()
  "Append a directory to the PYTHONPATH."
  (interactive
   (let ((string (read-directory-name 
          "Python package directory: " 
          nil 
          'my-history)))
     (setenv "PYTHONPATH" (concat (expand-file-name string)
                  (getenv ":PYTHONPATH"))))))

(defun pythonpath-dired-mode-hook ()
  (let ((setup_py (concat default-directory "setup.py"))
    (directory (expand-file-name default-directory)))
    ;;   (if (file-exists-p setup_py)
    (if (is-python-package-directory directory)
    (let ((pythonpath (concat (getenv "PYTHONPATH") ":" 
                  (expand-file-name directory))))
      (setenv "PYTHONPATH" pythonpath)
      (message (concat "PYTHONPATH=" (getenv "PYTHONPATH")))))))

(defun is-python-package-directory (directory)
  (let ((setup_py (concat directory "setup.py")))
    (file-exists-p setup_py)))

(add-hook 'dired-mode-hook 'pythonpath-dired-mode-hook)

Hope this helps.


回答 14

如果有人在寻找一种方法来将Pylint作为PyCharm中的外部工具运行并使其与他们的虚拟环境一起工作(为什么我要问这个问题),那么我将通过以下方式解决它:

  1. 在PyCharm>首选项>工具>外部工具中,添加或编辑pylint的项目。
  2. 在“编辑工具”对话框的“工具设置”中,将“程序”设置为使用python解释器目录中的pylint: $PyInterpreterDirectory$/pylint
  3. 在“参数”字段中设置其他参数,例如: --rcfile=$ProjectFileDir$/pylintrc -r n $FileDir$
  4. 将工作目录设置为 $FileDir$

现在,使用pylint作为外部工具,可以在使用公共配置文件选择的任何目录上运行pylint,并使用为项目配置的任何解释器(大概是您的virtualenv解释器)。

In case anybody is looking for a way to run pylint as an external tool in PyCharm and have it work with their virtual environments (why I came to this question), here’s how I solved it:

  1. In PyCharm > Preferences > Tools > External Tools, Add or Edit an item for pylint.
  2. In the Tool Settings of the Edit Tool dialog, set Program to use pylint from the python interpreter directory: $PyInterpreterDirectory$/pylint
  3. Set your other parameters in the Parameters field, like: --rcfile=$ProjectFileDir$/pylintrc -r n $FileDir$
  4. Set your working directory to $FileDir$

Now using pylint as an external tool will run pylint on whatever directory you have selected using a common config file and use whatever interpreter is configured for your project (which presumably is your virtualenv interpreter).


回答 15

这是一个老问题,但是没有可接受的答案,所以我建议这样做:将two.py中的import语句更改为:

from .. import one

在我当前的环境(Python 3.6,使用pylint 2.3.1的VSCode)中,这清除了标记的语句。

This is an old question but has no accepted answer, so I’ll suggest this: change the import statement in two.py to read:

from .. import one

In my current environment (Python 3.6, VSCode using pylint 2.3.1) this clears the flagged statement.


回答 16

我找到了一个不错的答案。编辑您的pylintrc并在master中添加以下内容

init-hook="import imp, os; from pylint.config import find_pylintrc; imp.load_source('import_hook', os.path.join(os.path.dirname(find_pylintrc()), 'import_hook.py'))"

I found a nice answer. Edit your pylintrc and add the following in master

init-hook="import imp, os; from pylint.config import find_pylintrc; imp.load_source('import_hook', os.path.join(os.path.dirname(find_pylintrc()), 'import_hook.py'))"

回答 17

安装Python时,可以设置路径。如果已经定义了路径,那么您可以在VS Code中进行操作,按Ctrl + Shift + P并键入Python:选择“解释器”并选择Python的更新版本。请点击此链接以获取更多信息,https://code.visualstudio.com/docs/python/environments

When you install Python, you can set up the path. If path is already defined then what you can do is within VS Code, hit Ctrl+Shift+P and type Python: Select Interpreter and select updated version of Python. Follow this link for more information, https://code.visualstudio.com/docs/python/environments


回答 18

如果使用vscode,请确保您的软件包目录不在_pychache__目录中。

if you using vscode,make sure your package directory is out of the _pychache__ directory.


回答 19

如果您在Linux中使用Cython,则解决了删除module.cpython-XXm-X-linux-gnu.so项目目标目录中的文件的问题。

If you are using Cython in Linux, I resolved removing module.cpython-XXm-X-linux-gnu.so files in my project target directory.


回答 20

只需在.vscode / settings.json文件中添加此代码

,“ python.linting.pylintPath”:“ venv / bin / pylint”

这将通知pylint的位置(这是python的错误检查器)

just add this code in .vscode/settings.json file

,”python.linting.pylintPath”: “venv/bin/pylint”

This will notify the location of pylint(which is an error checker for python)


回答 21

您好,我能够从其他目录导入软件包。我只是做了以下事情:注意:我正在使用VScode

创建Python软件包的步骤使用Python软件包确实非常简单。您需要做的只是:

创建一个目录,并为其指定软件包的名称。将类放进去。在目录中创建一个初始化 .py文件

例如:您有一个名为Framework的文件夹,其中保存了所有自定义类,您的工作是在名为Framework的文件夹内创建一个init .py文件。

在导入时,您需要以这种方式导入->

从Framework导入库

因此E0401错误消失了,Framework是您刚在其中创建init .py 的文件夹,而base是您要自定义的模块,您需要将其导入并在该模块上工作,希望它能有所帮助!!!

Hello i was able to import the packages from different directory. I just did the following: Note: I am using VScode

Steps to Create a Python Package Working with Python packages is really simple. All you need to do is:

Create a directory and give it your package’s name. Put your classes in it. Create a init.py file in the directory

For example: you have a folder called Framework where you are keeping all the custom classes there and your job is to just create a init.py file inside the folder named Framework.

And while importing you need to import in this fashion—>

from Framework import base

so the E0401 error disappears Framework is the folder where you just created init.py and base is your custom module which you are required to import into and work upon Hope it helps!!!!


django导入错误-没有名为core.management的模块

问题:django导入错误-没有名为core.management的模块

好的,我看到很多这些错误。我已经尝试了所有我想做的事情,但是还没有弄清楚。

我正在开发运行python 2.5和Django 1.3的开发服务器。在解压缩tar.gz下载文件后,使用python setup.py install安装了Django 1.3。

一切正常,我很少需要运行,manage.py但是正在尝试使用新的staticfiles应用程序,并且遇到了问题。

python manage.py collectstatic
Traceback (most recent call last):
  File "manage.py", line 2, in <module>
    from django.core.management import execute_manager
ImportError: No module named core.management

好的,所以我有PATH问题。

Django安装中,我再次检查site-packages目录。

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"
/usr/lib/python2.5/site-packages

好的,让我们检查一下我拥有的东西,echo $ PYTHON_PATH为空,所以我将其设置为

export PYTHON_PATH=/usr/lib/python2.5/site-packages/django

仍然没有运气。让我们检查sys.path怎么说

>>> import sys
>>> print sys.path
['', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/django', '/var/lib/python-support/python2.5']

路径在那里,我什至用内容创建了/usr/lib/python2.5/site-packages/django.pth

cat /usr/lib/python2.5/site-packages/django.pth 
/usr/lib/python2.5/site-packages/django/

有人知道这里发生了什么吗?

我在通往的道路上发现了一个符号链接,但没有出现新的错误。

python manage.py collectstatic
Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    execute_manager(settings)
  File "/usr/lib/python2.5/site-packages/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/usr/lib/python2.5/site-packages/django/core/management/__init__.py", line 349, in execute
    version=get_version(),
  File "/usr/lib/python2.5/site-packages/django/__init__.py", line 12, in get_version
    from django.utils.version import get_svn_revision
ImportError: No module named utils.version

我还尝试创建一个新项目,以查看是否存在任何问题,并得到相同的utils.version错误。

侧面节点:#django的Unode帮助了我一点,在同一台计算机上设置了virtualenv并克服了错误,因此仍不确定此处的实际安装如何,但是似乎不在django项目中,而在django中/ python安装。

Ok, I see plenty of these errors around. I have tried everything I know to do and have yet to figure this out.

I am working on a development server running python 2.5 and Django 1.3. Django 1.3 was installed using python setup.py install after unpacking the tar.gz download.

All works well, I seldom have the need to run manage.py but am trying to use the new staticfiles app and am running into problems.

python manage.py collectstatic
Traceback (most recent call last):
  File "manage.py", line 2, in <module>
    from django.core.management import execute_manager
ImportError: No module named core.management

Ok, so I have PATH issue.

From Django install I double check my site-packages directory.

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"
/usr/lib/python2.5/site-packages

Ok, let’s check out what I have, echo $PYTHON_PATH was empty, so I set it

export PYTHON_PATH=/usr/lib/python2.5/site-packages/django

Still no luck. Lets check what sys.path has to say

>>> import sys
>>> print sys.path
['', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/django', '/var/lib/python-support/python2.5']

path is there, I even created /usr/lib/python2.5/site-packages/django.pth with contents

cat /usr/lib/python2.5/site-packages/django.pth 
/usr/lib/python2.5/site-packages/django/

Anyone got an clues to what is going on here?

I found a symlink further up the path that was getting in the way, but no on to a new error.

python manage.py collectstatic
Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    execute_manager(settings)
  File "/usr/lib/python2.5/site-packages/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/usr/lib/python2.5/site-packages/django/core/management/__init__.py", line 349, in execute
    version=get_version(),
  File "/usr/lib/python2.5/site-packages/django/__init__.py", line 12, in get_version
    from django.utils.version import get_svn_revision
ImportError: No module named utils.version

I also tried creating a new project to see if there were any issues there and get the same utils.version error.

Side node: Unode from #django helped me a bit, set up virtualenv on same machine and got past the errors so still not sure what is up with this actual install here, but it seems to not be in the django projects but in the django/python install.


回答 0

如果像我一样,您正在virtualenv中运行django,并收到此错误,请查看您的manage.py。第一行应定义用于运行脚本的python可执行文件。这应该是您的virtualenv的python的路径,但这是/ usr / bin / python之类的错误,它不是相同的路径,并且将使用全局python环境(并且缺少软件包)。只需将路径更改为virtualenv中python可执行文件的路径即可。

您也可以用替换您的shebang线#!/usr/bin/env python。如果您首先激活了virtualenv,这应该使用适当的python环境和解释器(我假设您知道如何执行此操作)。

If, like me, you are running your django in a virtualenv, and getting this error, look at your manage.py. The first line should define the python executable used to run the script. This should be the path to your virtualenv’s python, but it is something wrong like /usr/bin/python, which is not the same path and will use the global python environment (and packages will be missing). Just change the path into the path to the python executable in your virtualenv.

You can also replace your shebang line with #!/usr/bin/env python. This should use the proper python environment and interpreter provided that you activate your virtualenv first (I assume you know how to do this).


回答 1

如果您在virtualenv中,则需要先激活它,然后才能运行./manage.py’command’

source path/to/your/virtualenv/bin/activate

如果您在.bash_profile或.bashrc中配置workon

workon yourvirtualenvname

*请不要编辑您的manage.py文件,可能不是正确的方法,并且可能会给您将来的错误

If you are in a virtualenv you need to activate it before you can run ./manage.py ‘command’

source path/to/your/virtualenv/bin/activate

if you config workon in .bash_profile or .bashrc

workon yourvirtualenvname

*please dont edit your manage.py file maybe works by isnt the correct way and could give you future errors


回答 2

我遇到了同样的问题,因为我以超级用户身份安装Django,因此不在我的virtualenv中。你不应该做sudo pip install Django

而是以这种方式安装它:

$ source ./bin/activate
$ pip install Django

I had the same problem because I was installing Django as a super user, thus not in my virtualenv. You should not do sudo pip install Django

Instead, install it this way:

$ source ./bin/activate
$ pip install Django

回答 3

请用pip重新安装django:

sudo pip install --upgrade django==1.3

(将1.3替换为您的Django版本)

Please, reinstall django with pip:

sudo pip install --upgrade django==1.3

(Replace 1.3 to your django version)


回答 4

众所周知,这是一个路径问题。

我的自定义软件包的基础与/ etc / profile中设置的目录共享一个名称。软件包位于Web服务器的其他位置。因此,我从$ PYTHONPATH中删除了令人反感的条目,并且一切顺利!

谢谢您的帮助。

As known this was a path issue.

the base of my custom packages shared a name with a directory set in a /etc/profile. The packages were in a different location however for the webserver. So I removed the offending entries from my $PYTHONPATH and was good to go!

Thanks for the help.


回答 5

此问题的另一个可能原因是,您的操作系统默认情况下运行python3。

您必须明确地执行以下操作: python2 manage.py

或您需要编辑的shebang manage.py,如下所示:

#!/usr/bin/env python2

或者,如果您使用的是python3:

#!/usr/bin/env python3

Another possible reason for this problem is that your OS runs python3 by default.

Either you have to explicitly do: python2 manage.py

or you need to edit the shebang of manage.py, like so:

#!/usr/bin/env python2

or if you are using python3:

#!/usr/bin/env python3

回答 6

而试图在运行嵌入式系统(当然使用Django的)我有这个错误树莓派2(并且不是一个VM

运行此:

 sudo pip install Django

搞定了!

  • 以防万一使用Raspbian / Jessie的人得到了这个

I had this error while trying to run an embedded system (using django of course) on a Raspberry Pi 2 (and not a VM)

Running this:

 sudo pip install Django

Made the trick!

  • just in case a fellow using Raspbian/Jessie gets this

回答 7

您可能正在使用virtualenvwrapper。不要忘记通过运行以下命令来选择您的环境:

$ workon env_name

You are probably using virtualenvwrapper. Don’t forget to select your enviroment by running:

$ workon env_name

回答 8

对我来说,我的服务器使用的是Python 2.4。我只是查找了安装在服务器上的Python 2.7,并创建了一个别名。

alias python=python2.7

如果您需要了解更多信息,我在这里找到了解决方案

For me, my server was using Python 2.4. I simply looked up Python 2.7, which was installed on my server, and created an alias.

alias python=python2.7

If you need to know more, I found the solution here


回答 9

尝试创建新应用时遇到了同样的问题。如果您编写python manage.py startapp myapp,则它将查找usr / bin / python。但是您需要这个“ python ”,它位于虚拟环境路径的/ bin目录中。我通过提及virtualenv的python路径来解决此问题,如下所示:

<env path>/bin/python manage.py startapp myapp

I was getting the same problem while I trying to create a new app. If you write python manage.py startapp myapp, then it looks for usr/bin/python. But you need this “python” which is located in /bin directory of your virtual env path. I solved this by mentioning the virtualenv’s python path just like this:

<env path>/bin/python manage.py startapp myapp

回答 10

尝试更改您的manage.py的第一行。

更改

#!/usr/bin/python

通过

#!/usr/bin/env python

Try change your first line of manage.py.

Change

#!/usr/bin/python

by

#!/usr/bin/env python

回答 11

python3 manage.py runserver

检查Python版本

python3 manage.py runserver

Check version of Python


回答 12

解决了!!!

在寻找了年龄并尝试了所有其他不可行的建议之后,我终于找到了适合我的设置的解决方案。

我的设置/方案:

  • Windows,Python27
  • 我的Django项目通过svn签出
  • 在新文件夹中运行python manage.py runserver时,出现导入错误
  • python manage.py runserver曾经在原始文件夹(我会提交更改)中使用,直到删除它为止

删除manage.py同一目录中名为django的所有文件夹

没错…删除文件夹“ django”后,该文件夹仅包含__init__.py文件…我可以再次运行服务器!

不知道为什么

Solved it!!!

After searching for ages and trying all these other suggestions which didn’t work, I finally found the solution for my setup.

My setup/scenario:

  • Windows, Python27
  • My django project is checked out via svn
  • when running python manage.py runserver in the new folder, I got the import error
  • python manage.py runserver used to work in the original folder (which I would commit changes from) until I deleted it

Solution

Remove any the folder named django in the same directory of manage.py

Thats right…as soon as I removed the folder “django” which only contained a __init__.py file…I could run the server again!

Have no idea why though


回答 13

对于使用Django 1.6或更高版本的用户,请注意execute_manager已删除。有张贴在第二SO答案的解决方案在这里

For those of you using Django 1.6 or newer, note that execute_manager was removed. There is a solution posted in the second SO answer here.


回答 14

将python python路径存储在一个变量中并执行。

python_path= `which python` 
$python_path manage.py runserver

Store the python python path in a variable and execute.This would include the otherwise missing packages.

python_path= `which python` 
$python_path manage.py runserver

回答 15

我有一个类似的问题。PyCharm无法运行服务器,但是我可以从命令行运行它。我尝试使用哪个python,然后确保PyCharm是相同的解释器,然后一切正常。

I had a similar problem. PyCharm couldn’t run the server but I could run it from the command line. I tried which python and then made sure that PyCharm was same interpreter and then everything worked OK.


回答 16

当未安装django时,通常会发生此错误。如果您已经安装了django但仍然遇到相同的错误,则必须在单独的虚拟环境中工作。您还需要在虚拟环境中安装django。当您在虚拟机的外壳中时,只需执行以下操作:

pip安装Django

这是因为虚拟机具有单独的文件系统,即使将Django安装在您的系统上,它也无法识别。

This error usually occurs when django is not installed. If you have already installed django but still getting the same error, then you must be working in separate virtual environment. You need to install django in your virtual environmnent as well. When you are in shell of virtual machine simply do this:

pip install django

It is because virtual machine has separate file system, it doesn’t recognize django even if it is installed on your system.


回答 17

我通过将#PATH =“ $ VIRTUAL_ENV / bin:$ PATH”更改为PATH =“ $ PATH:$ VIRTUAL_ENV / bin”来解决此问题,由于对我不明显的原因,virtualenv目录中的python可执行文件看不到Django,但安装的Python呢。

I fixed this problem by changing #PATH=”$VIRTUAL_ENV/bin:$PATH” to PATH=”$PATH:$VIRTUAL_ENV/bin” For reasons not obvious to me the python executable in the virtualenv dir does not see django but the normally installed python does.


回答 18

================================解决方案=============== =========================

首先转到:virtualenv

通过运行以下命令:source bin / activate

并安装django,因为您收到与“ import django”相关的错误:

pip install django

然后运行:

python manage.py runserver

(注意:请将“ runserver”更改为要运行的程序名称)

对于同一问题,它在我的情况下有效。=================================提要================= =========================

ERROR:
(Development) Rakeshs-MacBook-Pro:src rakesh$ python manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    import django
ModuleNotFoundError: No module named 'django'

在处理上述异常期间,发生了另一个异常:

Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
(Development) Rakeshs-MacBook-Pro:src rakesh$ 
(Development) Rakeshs-MacBook-Pro:src rakesh$ 
(Development) Rakeshs-MacBook-Pro:src rakesh$ python -Wall manage.py test
Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'

在处理上述异常期间,发生了另一个异常:

Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    import django
ModuleNotFoundError: No module named 'django'

在处理上述异常期间,发生了另一个异常:

Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

安装Django之后:

(Development) MacBook-Pro:src rakesh$ pip install django
Collecting django
  Downloading https://files.pythonhosted.org/packages/51/1a/e0ac7886c7123a03814178d7517dc822af0fe51a72e1a6bff26153103322/Django-2.1-py3-none-any.whl (7.3MB)
    100% |████████████████████████████████| 7.3MB 1.1MB/s 
Collecting pytz (from django)
  Downloading https://files.pythonhosted.org/packages/30/4e/27c34b62430286c6d59177a0842ed90dc789ce5d1ed740887653b898779a/pytz-2018.5-py2.py3-none-any.whl (510kB)
    100% |████████████████████████████████| 512kB 4.7MB/s 
Installing collected packages: pytz, django

解决后:

(Development) MacBook-Pro:src rakesh$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

August 05, 2018 - 04:39:02
Django version 2.1, using settings 'trydjango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[05/Aug/2018 04:39:15] "GET / HTTP/1.1" 200 16348
[05/Aug/2018 04:39:15] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304
Not Found: /favicon.ico
[05/Aug/2018 04:39:16] "GET /favicon.ico HTTP/1.1" 404 1976

祝好运!!

==================================SOLUTION=========================================

First goto: virtualenv

by running the command: source bin/activate

and install django because you are getting the error related to ‘import django’:

pip install django

Then run:

python manage.py runserver

(Note: please change ‘runserver’ to the program name you want to run)

For the same issue, it worked in my case. ==================================Synopsis=========================================

ERROR:
(Development) Rakeshs-MacBook-Pro:src rakesh$ python manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    import django
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
(Development) Rakeshs-MacBook-Pro:src rakesh$ 
(Development) Rakeshs-MacBook-Pro:src rakesh$ 
(Development) Rakeshs-MacBook-Pro:src rakesh$ python -Wall manage.py test
Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    import django
ModuleNotFoundError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

AFTER INSTALLATION of django:

(Development) MacBook-Pro:src rakesh$ pip install django
Collecting django
  Downloading https://files.pythonhosted.org/packages/51/1a/e0ac7886c7123a03814178d7517dc822af0fe51a72e1a6bff26153103322/Django-2.1-py3-none-any.whl (7.3MB)
    100% |████████████████████████████████| 7.3MB 1.1MB/s 
Collecting pytz (from django)
  Downloading https://files.pythonhosted.org/packages/30/4e/27c34b62430286c6d59177a0842ed90dc789ce5d1ed740887653b898779a/pytz-2018.5-py2.py3-none-any.whl (510kB)
    100% |████████████████████████████████| 512kB 4.7MB/s 
Installing collected packages: pytz, django

AFTER RESOLVING:

(Development) MacBook-Pro:src rakesh$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

August 05, 2018 - 04:39:02
Django version 2.1, using settings 'trydjango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[05/Aug/2018 04:39:15] "GET / HTTP/1.1" 200 16348
[05/Aug/2018 04:39:15] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348
[05/Aug/2018 04:39:15] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304
Not Found: /favicon.ico
[05/Aug/2018 04:39:16] "GET /favicon.ico HTTP/1.1" 404 1976

Good luck!!


回答 19

您的项目是使用django1.3之前的旧版本django-admin.py创建的

要解决此问题,请创建另一个django项目并复制其manage.py并将其粘贴到旧的项目中

your project is created using an old version of django-admin.py, older than django1.3

to fix this create another django project and copy its manage.py and paste it in the old one


回答 20

完全同意这是一个路径问题,但是首先,我遇到了同样的错误。这是由于在设置虚拟环境时为我的Python可执行文件使用了相对路径的错误。我这样做了:

virtualenv -p ~/python_runtimes/2.7.3/bin/python venv2.7.3 --distribute

相反,我不得不给出Python可执行文件的完整路径。

哈林HTH

Agreed completely that this is a path issue but fwiw, I had this same error. It was due to the mistake of using a relative path for my Python executable when setting up my virtual environment. I had done this:

virtualenv -p ~/python_runtimes/2.7.3/bin/python venv2.7.3 --distribute

Instead I had to give the full path to the Python executable.

HTH, Harlin


回答 21

来源〜/ blog-venv / bin / activate

在此处选择您的virtualenv替换“ blog-venv”。

source ~/blog-venv/bin/activate

pick your virtualenv to replace “blog-venv” here.


回答 22

确保您在路径上使用正确的目录运行正确的Python实例。就我而言,此错误是python由偶然运行可执行文件引起的-我实际上是在python2.7框架和库下安装了Django 。由于virtualenv也可能发生相同的情况。

Be sure you’re running the right instance of Python with the right directories on the path. In my case, this error resulted from running the python executable by accident – I had actually installed Django under the python2.7 framework & libraries. The same could happen as a result of virtualenv as well.


回答 23

好的,它像这样:

您已经创建了一个虚拟环境,而django模块仅属于该环境。由于virtualenv会将其自身与其他所有事物隔离开,因此您会看到这一点。

进行以下操作以获得进一步的帮助:

http://www.swegler.com/becky/blog/2011/08/27/python-django-mysql-on-windows-7-part-i-getting-started/

1.您可以切换到虚拟环境存储的目录,然后运行django模块。

2.或者您可以通过运行pip或easy_install将django全局安装到python-> site-packages

使用pip的命令:pip install django

然后这样做:

导入django打印(django.get_version())(取决于您使用的python版本。这适用于python 3+系列)

然后您可以运行以下命令:python manage.py runserver并通过输入:localhost:8000在Web浏览器上进行检查,您应该看到django驱动的页面。

希望这可以帮助。

Okay so it goes like this:

You have created a virtual environment and django module belongs to that environment only.Since virtualenv isolates itself from everything else,hence you are seeing this.

go through this for further assistance:

http://www.swegler.com/becky/blog/2011/08/27/python-django-mysql-on-windows-7-part-i-getting-started/

1.You can switch to the directory where your virtual environment is stored and then run the django module.

2.Alternatively you can install django globally to your python->site-packages by either running pip or easy_install

Command using pip: pip install django

then do this:

import django print (django.get_version()) (depending on which version of python you use.This for python 3+ series)

and then you can run this: python manage.py runserver and check on your web browser by typing :localhost:8000 and you should see django powered page.

Hope this helps.


回答 24

我在发出startapp命令之前“之前”将新应用程序的名称包含在settings.py的INSTALLED_APPS列表中。删除列表条目后,就可以创建应用了。

I included the name of the new App to the INSTALLED_APPS list in the settings.py “before” I issued the startapp command. Once I removed the list entry, I could create the app.


回答 25

我通过使用’django-admin’命令来解决此问题,如下所示:

django-admin startproject _project_name

只需删除附加到“ django-admin”的“ .py”

I solved this problem by using ‘django-admin’ command as following instead:

django-admin startproject _project_name

just remove the “.py” attached to “django-admin”


回答 26

调用一个应用程序site也可以重现此问题。

Having an application called site can reproduce this issue either.


回答 27

我之所以忘记了,是因为我忘记使用来安装Django pip -U,因此它仅适用于运行Django应用的用户。要运行manage.py我必须做

sudo su -s /bin/bash MY_DJANGO_USER
/PATH/TO/MY/APP/manage.py

I got this due to forgetting that I installed Django using pip -U, so it was only available to the user running my Django app. To run manage.py I had to do

sudo su -s /bin/bash MY_DJANGO_USER
/PATH/TO/MY/APP/manage.py

回答 28

你们所有人都没有提到有人“像我”会在安装virtualenv之前安装django …因此,对于所有此类人,如果这样做,…在激活virtualenv..i之后重新安装django。希望这可以帮助

all of you guys didn’t mention a case where someone “like me” would install django befor installing virtualenv…so for all the people of my kind ther if you did that…reinstall django after activating the virtualenv..i hope this helps


如何正确确定当前脚本目录?

问题:如何正确确定当前脚本目录?

我想看看确定python中当前脚本目录的最佳方法是什么?

我发现,由于调用python代码的方式很多,很难找到一个好的解决方案。

这里有一些问题:

  • __file__如果脚本与执行没有定义execexecfile
  • __module__ 仅在模块中定义

用例:

  • ./myfile.py
  • python myfile.py
  • ./somedir/myfile.py
  • python somedir/myfile.py
  • execfile('myfile.py') (来自另一个脚本,该脚本可以位于另一个目录中,并且可以具有另一个当前目录。

我知道没有完美的解决方案,但是我正在寻找能够解决大多数情况的最佳方法。

最常用的方法是,os.path.dirname(os.path.abspath(__file__))但是如果您使用来从另一个脚本执行脚本,则此方法实际上不起作用exec()

警告

使用当前目录的任何解决方案都会失败,这可能会因调用脚本的方式而有所不同,或者可以在运行的脚本中进行更改。

I would like to see what is the best way to determine the current script directory in Python.

I discovered that, due to the many ways of calling Python code, it is hard to find a good solution.

Here are some problems:

  • __file__ is not defined if the script is executed with exec, execfile
  • __module__ is defined only in modules

Use cases:

  • ./myfile.py
  • python myfile.py
  • ./somedir/myfile.py
  • python somedir/myfile.py
  • execfile('myfile.py') (from another script, that can be located in another directory and that can have another current directory.

I know that there is no perfect solution, but I’m looking for the best approach that solves most of the cases.

The most used approach is os.path.dirname(os.path.abspath(__file__)) but this really doesn’t work if you execute the script from another one with exec().

Warning

Any solution that uses current directory will fail, this can be different based on the way the script is called or it can be changed inside the running script.


回答 0

os.path.dirname(os.path.abspath(__file__))

确实是您将获得的最好的。

exec/ 执行脚本是不寻常的execfile。通常,您应该使用模块基础结构来加载脚本。如果必须使用这些方法,我建议设置__file__globals传递给脚本,以便它可以读取该文件名。

没有其他方法可以在执行代码中获取文件名:如您所述,CWD可能位于完全不同的位置。

os.path.dirname(os.path.abspath(__file__))

is indeed the best you’re going to get.

It’s unusual to be executing a script with exec/execfile; normally you should be using the module infrastructure to load scripts. If you must use these methods, I suggest setting __file__ in the globals you pass to the script so it can read that filename.

There’s no other way to get the filename in execed code: as you note, the CWD may be in a completely different place.


回答 1

如果您确实想解决通过调用脚本的情况,则execfile(...)可以使用该inspect模块推断文件名(包括路径)。据我所知,这将适用于您列出的所有情况:

filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))

If you really want to cover the case that a script is called via execfile(...), you can use the inspect module to deduce the filename (including the path). As far as I am aware, this will work for all cases you listed:

filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))

回答 2

#!/usr/bin/env python
import inspect
import os
import sys

def get_script_dir(follow_symlinks=True):
    if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze
        path = os.path.abspath(sys.executable)
    else:
        path = inspect.getabsfile(get_script_dir)
    if follow_symlinks:
        path = os.path.realpath(path)
    return os.path.dirname(path)

print(get_script_dir())

它适用于CPython,Jython,Pypy。如果使用以下命令执行脚本,它将起作用execfile()sys.argv[0]__file__基于解决方案会在这里失败)。如果脚本位于可执行zip文件(/卵)中,则该脚本有效。如果脚本是PYTHONPATH=/path/to/library.zip python -mscript_to_run从zip文件“导入”()的,则该脚本有效。在这种情况下,它将返回存档路径。如果脚本被编译成独立的可执行文件(sys.frozen),它将起作用。它适用于符号链接(realpath消除了符号链接)。它在交互式解释器中工作;在这种情况下,它将返回当前的工作目录。

#!/usr/bin/env python
import inspect
import os
import sys

def get_script_dir(follow_symlinks=True):
    if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze
        path = os.path.abspath(sys.executable)
    else:
        path = inspect.getabsfile(get_script_dir)
    if follow_symlinks:
        path = os.path.realpath(path)
    return os.path.dirname(path)

print(get_script_dir())

It works on CPython, Jython, Pypy. It works if the script is executed using execfile() (sys.argv[0] and __file__ -based solutions would fail here). It works if the script is inside an executable zip file (/an egg). It works if the script is “imported” (PYTHONPATH=/path/to/library.zip python -mscript_to_run) from a zip file; it returns the archive path in this case. It works if the script is compiled into a standalone executable (sys.frozen). It works for symlinks (realpath eliminates symbolic links). It works in an interactive interpreter; it returns the current working directory in this case.


回答 3

在Python 3.4+中,您可以使用更简单的pathlib模块:

from inspect import currentframe, getframeinfo
from pathlib import Path

filename = getframeinfo(currentframe()).filename
parent = Path(filename).resolve().parent

In Python 3.4+ you can use the simpler pathlib module:

from inspect import currentframe, getframeinfo
from pathlib import Path

filename = getframeinfo(currentframe()).filename
parent = Path(filename).resolve().parent

You can also use __file__ to avoid the inspect module altogether:

from pathlib import Path
parent = Path(__file__).resolve().parent

回答 4

os.path...方法是Python 2中的“完成的事情”。

在Python 3中,您可以找到脚本目录,如下所示:

from pathlib import Path
cwd = Path(__file__).parents[0]

The os.path... approach was the ‘done thing’ in Python 2.

In Python 3, you can find directory of script as follows:

from pathlib import Path
cwd = Path(__file__).parents[0]

回答 5

只需使用os.path.dirname(os.path.abspath(__file__))并非常仔细地检查使用情况下是否真的需要exec。如果您不能将脚本用作模块,则可能是设计麻烦的迹象。

请记住,Python#8的Zen,如果您认为有一个必须在其中使用的用例exec,那么请告诉我们有关问题背景的更多详细信息。

Just use os.path.dirname(os.path.abspath(__file__)) and examine very carefully whether there is a real need for the case where exec is used. It could be a sign of troubled design if you are not able to use your script as a module.

Keep in mind Zen of Python #8, and if you believe there is a good argument for a use-case where it must work for exec, then please let us know some more details about the background of the problem.


回答 6

import os
cwd = os.getcwd()

你想做什么?我不确定“当前脚本目录”到底是什么意思。您给出的用例的预期输出是什么?

Would

import os
cwd = os.getcwd()

do what you want? I’m not sure what exactly you mean by the “current script directory”. What would the expected output be for the use cases you gave?


回答 7

首先..如果我们正在讨论注入匿名代码的方式,那么这里有几个用例。

code.compile_command()
code.interact()
imp.load_compiled()
imp.load_dynamic()
imp.load_module()
__builtin__.compile()
loading C compiled shared objects? example: _socket?)

但是,真正的问题是,您的目标是什么-您是否要强制实施某种安全性?或者您只是对正在加载的内容感兴趣。

如果您对安全性感兴趣,则通过exec / execfile导入的文件名无关紧要-您应该使用rexec,它提供以下内容:

该模块包含RExec类,该类支持r_eval(),r_execfile(),r_exec()和r_import()方法,它们是标准Python函数eval(),execfile()以及exec和import语句的受限版本。在此受限环境中执行的代码只能访问被认为安全的模块和功能;您可以根据需要为RExec子类添加或删除功能。

但是,如果这更多是学术上的追求,那么您可以通过以下两种愚蠢的方法来进行深入研究。

示例脚本:

./deep.py

print ' >> level 1'
execfile('deeper.py')
print ' << level 1'

./deeper.py

print '\t >> level 2'
exec("import sys; sys.path.append('/tmp'); import deepest")
print '\t << level 2'

/tmp/deepest.py

print '\t\t >> level 3'
print '\t\t\t I can see the earths core.'
print '\t\t << level 3'

./codespy.py

import sys, os

def overseer(frame, event, arg):
    print "loaded(%s)" % os.path.abspath(frame.f_code.co_filename)

sys.settrace(overseer)
execfile("deep.py")
sys.exit(0)

输出量

loaded(/Users/synthesizerpatel/deep.py)
>> level 1
loaded(/Users/synthesizerpatel/deeper.py)
    >> level 2
loaded(/Users/synthesizerpatel/<string>)
loaded(/tmp/deepest.py)
        >> level 3
            I can see the earths core.
        << level 3
    << level 2
<< level 1

当然,这是一种占用大量资源的方法,您会跟踪所有代码。效率不是很高。但是,我认为这是一种新颖的方法,因为即使您深入巢穴,它仍然可以继续工作。您无法覆盖“评估”。虽然可以覆盖execfile()。

注意,此方法仅覆盖exec / execfile,而不覆盖“ import”。对于更高级别的“模块”负载挂钩,您可能可以使用 sys.path_hooks(由PyMOTW致谢)。

多数民众赞成在我的头上。

First.. a couple missing use-cases here if we’re talking about ways to inject anonymous code..

code.compile_command()
code.interact()
imp.load_compiled()
imp.load_dynamic()
imp.load_module()
__builtin__.compile()
loading C compiled shared objects? example: _socket?)

But, the real question is, what is your goal – are you trying to enforce some sort of security? Or are you just interested in whats being loaded.

If you’re interested in security, the filename that is being imported via exec/execfile is inconsequential – you should use rexec, which offers the following:

This module contains the RExec class, which supports r_eval(), r_execfile(), r_exec(), and r_import() methods, which are restricted versions of the standard Python functions eval(), execfile() and the exec and import statements. Code executed in this restricted environment will only have access to modules and functions that are deemed safe; you can subclass RExec add or remove capabilities as desired.

However, if this is more of an academic pursuit.. here are a couple goofy approaches that you might be able to dig a little deeper into..

Example scripts:

./deep.py

print ' >> level 1'
execfile('deeper.py')
print ' << level 1'

./deeper.py

print '\t >> level 2'
exec("import sys; sys.path.append('/tmp'); import deepest")
print '\t << level 2'

/tmp/deepest.py

print '\t\t >> level 3'
print '\t\t\t I can see the earths core.'
print '\t\t << level 3'

./codespy.py

import sys, os

def overseer(frame, event, arg):
    print "loaded(%s)" % os.path.abspath(frame.f_code.co_filename)

sys.settrace(overseer)
execfile("deep.py")
sys.exit(0)

Output

loaded(/Users/synthesizerpatel/deep.py)
>> level 1
loaded(/Users/synthesizerpatel/deeper.py)
    >> level 2
loaded(/Users/synthesizerpatel/<string>)
loaded(/tmp/deepest.py)
        >> level 3
            I can see the earths core.
        << level 3
    << level 2
<< level 1

Of course, this is a resource-intensive way to do it, you’d be tracing all your code.. Not very efficient. But, I think it’s a novel approach since it continues to work even as you get deeper into the nest. You can’t override ‘eval’. Although you can override execfile().

Note, this approach only coveres exec/execfile, not ‘import’. For higher level ‘module’ load hooking you might be able to use use sys.path_hooks (Write-up courtesy of PyMOTW).

Thats all I have off the top of my head.


回答 8

这是一个部分解决方案,仍然比到目前为止所有已发布的解决方案都要好。

import sys, os, os.path, inspect

#os.chdir("..")

if '__file__' not in locals():
    __file__ = inspect.getframeinfo(inspect.currentframe())[0]

print os.path.dirname(os.path.abspath(__file__))

现在所有电话都可以使用,但是如果有人使用 chdir()用来更改当前目录,则此操作也会失败。

笔记:

  • sys.argv[0]将无法正常工作,-c如果您使用以下命令执行脚本,则会返回python -c "execfile('path-tester.py')"
  • 我在https://gist.github.com/1385555发布了完整的测试,欢迎您进行改进。

Here is a partial solution, still better than all published ones so far.

import sys, os, os.path, inspect

#os.chdir("..")

if '__file__' not in locals():
    __file__ = inspect.getframeinfo(inspect.currentframe())[0]

print os.path.dirname(os.path.abspath(__file__))

Now this works will all calls but if someone use chdir() to change the current directory, this will also fail.

Notes:

  • sys.argv[0] is not going to work, will return -c if you execute the script with python -c "execfile('path-tester.py')"
  • I published a complete test at https://gist.github.com/1385555 and you are welcome to improve it.

回答 9

这在大多数情况下应该有效:

import os,sys
dirname=os.path.dirname(os.path.realpath(sys.argv[0]))

This should work in most cases:

import os,sys
dirname=os.path.dirname(os.path.realpath(sys.argv[0]))

回答 10

希望这会有所帮助:-如果您从任何地方运行脚本/模块,您将能够访问__file__变量,该变量是表示脚本位置的模块变量。

另一方面,如果您使用的是解释器,则您无权访问该变量,否则您将在其中获得名称,NameError并且os.getcwd()如果从其他位置运行文件,则将给您错误的目录。

在所有情况下,解决方案都应为您提供所需的信息:

from inspect import getsourcefile
from os.path import abspath
abspath(getsourcefile(lambda:0))

我尚未对其进行全面测试,但是它解决了我的问题。

Hopefully this helps:- If you run a script/module from anywhere you’ll be able to access the __file__ variable which is a module variable representing the location of the script.

On the other hand, if you’re using the interpreter you don’t have access to that variable, where you’ll get a name NameError and os.getcwd() will give you the incorrect directory if you’re running the file from somewhere else.

This solution should give you what you’re looking for in all cases:

from inspect import getsourcefile
from os.path import abspath
abspath(getsourcefile(lambda:0))

I haven’t thoroughly tested it but it solved my problem.


如何在Windows中添加到PYTHONPATH,以便找到我的模块/软件包?

问题:如何在Windows中添加到PYTHONPATH,以便找到我的模块/软件包?

我有一个托管所有Django应用程序的目录(C:\My_Projects)。我想将此目录添加到我的目录中,PYTHONPATH以便直接调用应用程序。

我尝试从Windows GUI()添加C:\My_Projects\;到Windows Path变量中My Computer > Properties > Advanced System Settings > Environment Variables。但是它仍然不读取coltrane模块并生成此错误:

错误:没有名为coltrane的模块

I have a directory which hosts all of my Django apps (C:\My_Projects). I want to add this directory to my PYTHONPATH so I can call the apps directly.

I tried adding C:\My_Projects\; to my Windows Path variable from the Windows GUI (My Computer > Properties > Advanced System Settings > Environment Variables). But it still doesn’t read the coltrane module and generates this error:

Error: No module named coltrane


回答 0

您知道在Windows上对我非常有效的方法。

My Computer > Properties > Advanced System Settings > Environment Variables >

只需将路径添加为C:\ Python27(或安装python的任何位置)

要么

然后在系统变量下创建一个名为的新变量PythonPath。在这个变量中C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\other-folders-on-the-path

这是对我有用的最好方法,我在提供的任何文档中都没有找到它。

编辑:对于那些谁无法获得它,请添加

C:\ Python27;

随之而来。否则它将永远无法正常工作

You know what has worked for me really well on windows.

My Computer > Properties > Advanced System Settings > Environment Variables >

Just add the path as C:\Python27 (or wherever you installed python)

OR

Then under system variables I create a new Variable called PythonPath. In this variable I have C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\other-folders-on-the-path

This is the best way that has worked for me which I hadn’t found in any of the docs offered.

EDIT: For those who are not able to get it, Please add

C:\Python27;

along with it. Else it will never work.


回答 1

Windows 7 Professional I修改了@mongoose_za的答案,以便更轻松地更改python版本:

  1. [右键单击]计算机>属性>高级系统设置>环境变量
  2. 点击“系统变量”下的[新建]
  3. 变量名称:PY_HOME,变量值:C:\ path \ to \ python \ version
  4. 点击[确定]
  5. 找到“路径”系统变量,然后单击[编辑]
  6. 将以下内容添加到现有变量中:

    %PY_HOME%;%PY_HOME%\ Lib;%PY_HOME%\ DLLs;%PY_HOME%\ Lib \ lib-tk;

  7. 单击[确定]关闭所有窗口。

最后,检查命令提示符并输入python。你应该看到

>python [whatever version you are using]

如果需要在版本之间进行切换,则只需修改PY_HOME变量以指向正确的目录。如果您需要安装多个python版本,这将更易于管理。

Windows 7 Professional I Modified @mongoose_za’s answer to make it easier to change the python version:

  1. [Right Click]Computer > Properties >Advanced System Settings > Environment Variables
  2. Click [New] under “System Variable”
  3. Variable Name: PY_HOME, Variable Value:C:\path\to\python\version
  4. Click [OK]
  5. Locate the “Path” System variable and click [Edit]
  6. Add the following to the existing variable:

    %PY_HOME%;%PY_HOME%\Lib;%PY_HOME%\DLLs;%PY_HOME%\Lib\lib-tk;

  7. Click [OK] to close all of the windows.

As a final sanity check open a command prompt and enter python. You should see

>python [whatever version you are using]

If you need to switch between versions, you only need to modify the PY_HOME variable to point to the proper directory. This is bit easier to manage if you need multiple python versions installed.


回答 2

从Windows命令行:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

要永久设置PYTHONPATH,请将该行添加到中autoexec.bat。或者,如果您通过“系统属性”编辑系统变量,则该变量也将被永久更改。

From Windows command line:

set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

To set the PYTHONPATH permanently, add the line to your autoexec.bat. Alternatively, if you edit the system variable through the System Properties, it will also be changed permanently.


回答 3

您只需将您的安装路径(前C:\ Python27 \)到PATH变量系统变量。然后关闭并打开命令行,并输入’python’

Just append your installation path (ex. C:\Python27\) to the PATH variable in System variables. Then close and open your command line and type ‘python’.


回答 4

这些解决方案有效,但是它们仅在您的计算机上适用于您的代码。我会在代码中添加几行,如下所示:

import sys
if "C:\\My_Python_Lib" not in sys.path:
    sys.path.append("C:\\My_Python_Lib")

那应该照顾你的问题

These solutions work, but they work for your code ONLY on your machine. I would add a couple of lines to your code that look like this:

import sys
if "C:\\My_Python_Lib" not in sys.path:
    sys.path.append("C:\\My_Python_Lib")

That should take care of your problems


回答 5

PythonPythonPath添加到Windows环境:

  1. 打开资源管理器。
  2. 右键单击左侧导航树面板中的“计算机”
  3. 选择上下文菜单底部的“属性”
  4. 选择“高级系统设置”
  5. 点击“环境变量…”高级”选项卡中的
  6. “系统变量”下

      • PY_HOME

        C:\Python27
      • PYTHONPATH

        %PY_HOME%\Lib;%PY_HOME%\DLLs;%PY_HOME%\Lib\lib-tk;C:\another-library
    1. 附加

      • path

        %PY_HOME%;%PY_HOME%\Scripts\

Adding Python and PythonPath to the Windows environment:

  1. Open Explorer.
  2. Right-click ‘Computer’ in the Navigation Tree Panel on the left.
  3. Select ‘Properties’ at the bottom of the Context Menu.
  4. Select ‘Advanced system settings’
  5. Click ‘Environment Variables…’ in the Advanced Tab
  6. Under ‘System Variables’:

    1. Add

      • PY_HOME

        C:\Python27
        
      • PYTHONPATH

        %PY_HOME%\Lib;%PY_HOME%\DLLs;%PY_HOME%\Lib\lib-tk;C:\another-library
        
    2. Append

      • path

        %PY_HOME%;%PY_HOME%\Scripts\
        

回答 6

在python中设置路径的更简单方法是:单击开始>我的电脑>属性>高级系统设置>环境变量>第二个窗口>

选择“路径”>“编辑”>,然后添加“; C:\ Python27 \; C:\ Python27 \ Scripts \”

链接:http : //docs.python-guide.org/en/latest/starting/install/win/

The easier way to set the path in python is : click start> My Computer >Properties > Advanced System Settings > Environment Variables > second windows >

select Path > Edit > and then add “;C:\Python27\;C:\Python27\Scripts\”

link :http://docs.python-guide.org/en/latest/starting/install/win/


回答 7

您需要添加到您的PYTHONPATH变量而不是Windows PATH变量。

http://docs.python.org/using/windows.html

You need to add to your PYTHONPATH variable instead of Windows PATH variable.

http://docs.python.org/using/windows.html


回答 8

您还可以在.pth文件c:\PythonX.X夹或中添加一个包含所需目录的文件\site-packages folder,这在我开发Python软件包时通常是我的首选方法。

有关更多信息,请参见此处

You can also add a .pth file containing the desired directory in either your c:\PythonX.X folder, or your \site-packages folder, which tends to be my preferred method when I’m developing a Python package.

See here for more information.


回答 9

import sys
sys.path.append("path/to/Modules")
print sys.path

这不会在重新启动后持续存在,也不会转换为其他文件。但是,如果您不想对系统进行永久性修改,那就太好了。

import sys
sys.path.append("path/to/Modules")
print sys.path

This won’t persist over reboots or get translated to other files. It is however great if you don’t want to make a permanent modification to your system.


回答 10

成功执行此操作的最简单方法是再次运行python安装程序(首次安装后),然后:

  1. 选择修改。
  2. 检查所需的可选功能,然后单击下一步。
  3. 到这里,在“高级选项”步骤中,您必须看到一个选项“将Python添加到环境变量”。只需检查该选项,然后单击“安装”即可。 安装完成后,将添加python环境变量,您可以在任何地方轻松使用python。

The easiest way to do that successfully, is to run the python installer again (after the first installation) and then:

  1. choose Modify.
  2. check the optional features which you want and click Next.
  3. here we go, in “Advanced Options” step you must see an option saying “Add Python to environment variables”. Just check that option and click Install. When the installation is completed, python environment variables are added and you can easily use python everywhere.

回答 11

在Windows上的Python 3.4中,当我将其添加到PATH环境变量而不是PYTHONPATH 时,它可以工作。就像您在D:\ Programming \ Python34中安装了Python 3.4一样,请将其添加到PATH环境变量的末尾

;D:\Programming\Python34

关闭并重新打开命令提示符,然后执行“ python”。它将打开python shell。这也解决了我的Sublime 3问题:“ python无法识别为内部或外部命令”

In Python 3.4 on windows it worked when I added it to PATH enviroment variable instead of PYTHONPATH. Like if you have installed Python 3.4 in D:\Programming\Python34 then add this at the end of your PATH environment variable

;D:\Programming\Python34

Close and reopen command prompt and execute ‘python’. It will open the python shell. This also fixed my Sublime 3 issue of ‘python is not recognized as an internal or external command’.


回答 12

可以从上面的一些说明中设置python 2.X路径。默认情况下,Python 3将安装在C:\ Users \\ AppData \ Local \ Programs \ Python \ Python35-32 \中,因此必须将此路径添加到Windows环境中的Path变量中。

The python 2.X paths can be set from few of the above instructions. Python 3 by default will be installed in C:\Users\\AppData\Local\Programs\Python\Python35-32\ So this path has to be added to Path variable in windows environment.


回答 13

要增强PYTHONPATH,请运行regedit并导航至KEY_LOCAL_MACHINE \ SOFTWARE \ Python \ PythonCore,然后选择要使用的python版本的文件夹。该文件夹内有一个标为PythonPath的文件夹,其中一个条目指定默认安装存储模块的路径。右键单击PythonPath并选择创建一个新密钥。您可能想在将要指定模块位置的项目后命名该密钥;这样,您可以轻松地划分和跟踪路径修改。

谢谢

To augment PYTHONPATH, run regedit and navigate to KEY_LOCAL_MACHINE \SOFTWARE\Python\PythonCore and then select the folder for the python version you wish to use. Inside this is a folder labelled PythonPath, with one entry that specifies the paths where the default install stores modules. Right-click on PythonPath and choose to create a new key. You may want to name the key after the project whose module locations it will specify; this way, you can easily compartmentalize and track your path modifications.

thanks


回答 14

Python使用PYTHONPATH环境变量来指定可在Windows上从中导入模块的目录列表。运行时,您可以检查sys.path变量以查看导入内容时将搜索哪些目录。

要从命令提示符设置此变量,请使用:set PYTHONPATH=list;of;paths

要从PowerShell设置此变量,请使用: $env:PYTHONPATH=’list;of;paths’在启动Python之前

建议通过“环境变量”设置全局设置此变量,因为任何版本的Python都可以使用它,而不是您打算使用的版本。在Windows FAQ文档的Python中阅读更多内容。

The PYTHONPATH environment variable is used by Python to specify a list of directories that modules can be imported from on Windows. When running, you can inspect the sys.path variable to see which directories will be searched when you import something.

To set this variable from the Command Prompt, use: set PYTHONPATH=list;of;paths.

To set this variable from PowerShell, use: $env:PYTHONPATH=’list;of;paths’ just before you launch Python.

Setting this variable globally through the Environment Variables settings is not recommended, as it may be used by any version of Python instead of the one that you intend to use. Read more in the Python on Windows FAQ docs.


回答 15

对于尝试使用Python 3.3+实现此功能的任何人,Windows安装程序现在都提供了一个将python.exe添加到系统搜索路径的选项。在文档中阅读更多内容。

For anyone trying to achieve this with Python 3.3+, the Windows installer now includes an option to add python.exe to the system search path. Read more in the docs.


回答 16

这个问题需要一个正确的答案:

只需使用site为此工作量身定制的标准包装即可!

这是怎么做的(在同一主题上回答我自己的问题的答案):


  1. 打开Python提示符并输入
>>> import site
>>> site.USER_SITE
'C:\\Users\\ojdo\\AppData\\Roaming\\Python\\Python37\\site-packages'
...
  1. 如果此文件夹尚不存在,请创建它:
...
>>> import os
>>> os.makedirs(site.USER_SITE)
...
  1. 手动或使用类似以下代码sitecustomize.py的内容在此文件夹中创建一个包含的内容的文件FIND_MY_PACKAGES。当然,您必须更改C:\My_Projects到自定义导入位置的正确路径。
...
>>> FIND_MY_PACKAGES = """
import site
site.addsitedir(r'C:\My_Projects')
"""
>>> filename = os.path.join(site.USER_SITE, 'sitecustomize.py')
>>> with open(filename, 'w') as outfile:
...     print(FIND_MY_PACKAGES, file=outfile)

下次启动Python时,C:\My_Projects它会出现在您的中sys.path,而无需触摸系统范围的设置。奖励:以上步骤也适用于Linux!

This question needs a proper answer:

Just use the standard package site, which was made for this job!

and here is how (plagiating my own answer to my own question on the very same topic):


  1. Open a Python prompt and type
>>> import site
>>> site.USER_SITE
'C:\\Users\\ojdo\\AppData\\Roaming\\Python\\Python37\\site-packages'
...
  1. Create this folder if it does not exist yet:
...
>>> import os
>>> os.makedirs(site.USER_SITE)
...
  1. Create a file sitecustomize.py in this folder containing the content of FIND_MY_PACKAGES, either manually or using something like the following code. Of course, you have to change C:\My_Projects to the correct path to your custom import location.
...
>>> FIND_MY_PACKAGES = """
import site
site.addsitedir(r'C:\My_Projects')
"""
>>> filename = os.path.join(site.USER_SITE, 'sitecustomize.py')
>>> with open(filename, 'w') as outfile:
...     print(FIND_MY_PACKAGES, file=outfile)

And the next time you start Python, C:\My_Projects is present in your sys.path, without having to touch system-wide settings. Bonus: the above steps work on Linux, too!


回答 17

安装ArcGIS Desktop时PYTHONPATH需要设置此变量ArcPY

PYTHONPATH=C:\arcgis\bin (您的ArcGIS Home Bin)

由于某种原因,当我在Windows 7 32位系统上使用安装程序时,从未设置过它。

This PYTHONPATH variable needs to be set for ArcPY when ArcGIS Desktop is installed.

PYTHONPATH=C:\arcgis\bin (your ArcGIS home bin)

For some reason it never was set when I used the installer on a Windows 7 32-bit system.


回答 18

我按照以下步骤在Windows 10中工作了。

在环境变量下,应仅将其添加到“ 系统变量 ”的PATH下,而不应将其添加到“ 用户变量 ”下。这是一个很大的混乱,如果我们错过了,那就会浪费时间。

另外,只需尝试导航到在计算机中安装Python的路径并将其添加到PATH。这只是工作而无需添加其他任何东西。

C:\ Users \ YourUserName \ AppData \ Local \ Programs \ Python \ Python37-32

最重要的是,关闭命令提示符,重新打开,然后再次尝试键入“ python”以查看版本详细信息。在环境变量中设置路径后,需要重新启动命令提示符以查看版本。

重新启动后,在命令提示符下键入python时,您应该能够看到python提示符和以下信息:

I got it worked in Windows 10 by following below steps.

Under environment variables, you should only add it under PATH of “System Variables” and not under “User Variables“. This is a great confusion and eats time if we miss it.

Also, just try to navigate to the path where you got Python installed in your machine and add it to PATH. This just works and no need to add any other thing in my case.I added just below path and it worked.

C:\Users\YourUserName\AppData\Local\Programs\Python\Python37-32

Most important, close command prompt, re-open and then re-try typing “python” to see the version details. You need to restart command prompt to see the version after setting up the path in environment variables.

After restarting, you should be able to see the python prompt and below info when typing python in command prompt:


回答 19

可能有些晚,但这是您将路径添加到Windows环境变量的方法。

  1. 转到环境变量选项卡,您可以通过按Windows键+ Pausa inter来执行此操作。

  2. 转到高级系统设置。

  3. 单击环境变量。

  4. 在下方的窗口中搜索“路径”值。

  5. 选择它

  6. 点击编辑

  7. 在该行的末尾,添加您的安装文件夹和到“脚本”文件夹的路由。

  8. 单击确定,接受器等。

完成后,输入cmd并从驱动器的任何位置编写python,它应该进入Python程序。

我的PC的示例(我有Python34

EXISTING_LINES;C:\Python34;C:\Python34\Scripts\

希望能帮助到你。

波哥大的问候

Maybe a little late, but this is how you add the path to the Windows Environment Variables.

  1. Go to the Environment Variables tab, you do this by pressing Windows key + Pausa inter.

  2. Go to Advanced System Settings.

  3. Click on Environment Variables.

  4. On the lower window search for the ‘Path’ value.

  5. Select it

  6. Click on Edit

  7. In the end of the line add your instalation folder and the route to ‘Scripts’ folder.

  8. Click ok, aceptar etc.

You’re done, enter cmd and write python from any location of your drive, it should enter the Python program.

Example with my pc (I have Python34)

EXISTING_LINES;C:\Python34;C:\Python34\Scripts\

Hope it helps.

Greetings from Bogotá


回答 20

您可以通过命令提示符轻松设置路径变量。

  1. 打开运行并编写cmd

  2. 在命令窗口中,输入以下内容:set path =%path%; C:\ python36

  3. 按回车。
  4. 检查写python并输入。您将看到python版本,如图所示。

You can set the path variable for easily by command prompt.

  1. Open run and write cmd

  2. In the command window write the following: set path=%path%;C:\python36

  3. press enter.
  4. to check write python and enter. You will see the python version as shown in the picture.


回答 21

虽然这个问题是关于“真正的” Python的,但确实是在网络搜索“ Iron Python PYTHONPATH”中出现的。对于像我一样困惑的Iron Python用户:事实证明Iron Python寻找一个名为的环境变量IRONPYTHONPATH

Linux / Mac / POSIX用户:不要忘记Windows不仅\用作路径分隔符,而且还;用作路径定界符,而不是:

While this question is about the ‘real’ Python, it did come up in a websearch for ‘Iron Python PYTHONPATH’. For Iron Python users as confused as I was: It turns out that Iron Python looks for an environment variable called IRONPYTHONPATH.

Linux/Mac/POSIX users: Don’t forget that not only does Windows use \ as path separators, but it also uses ; as path delimiters, not :.


如何使用python找出我的python路径?

问题:如何使用python找出我的python路径?

如何PYTHONPATH从Python脚本(或交互式外壳程序)中找出系统变量中列出了哪些目录?

How do I find out which directories are listed in my system’s PYTHONPATH variable, from within a Python script (or the interactive shell)?


回答 0

sys.path可能包括不是您的PYTHONPATH环境变量中特定的项目。要直接查询变量,请使用:

import os
try:
    user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
    user_paths = []

sys.path might include items that aren’t specifically in your PYTHONPATH environment variable. To query the variable directly, use:

import os
try:
    user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
    user_paths = []

回答 1

您可能还希望这样:

import sys
print(sys.path)

或者作为从终端的一行代码:

python -c "import sys; print('\n'.join(sys.path))"

注意:如果您安装了多个版本的Python,则应使用相应的命令python2python3

You would probably also want this:

import sys
print(sys.path)

Or as a one liner from the terminal:

python -c "import sys; print('\n'.join(sys.path))"

Caveat: If you have multiple versions of Python installed you should use a corresponding command python2 or python3.


回答 2

似乎无法编辑其他答案。有一个小错误,因为它仅适用于Windows。更通用的解决方案是使用os.sep,如下所示:

sys.path可能包含不是您的PYTHONPATH环境变量中特定的项目。要直接查询变量,请使用:

import os
os.environ['PYTHONPATH'].split(os.pathsep)

Can’t seem to edit the other answer. Has a minor error in that it is Windows-only. The more generic solution is to use os.sep as below:

sys.path might include items that aren’t specifically in your PYTHONPATH environment variable. To query the variable directly, use:

import os
os.environ['PYTHONPATH'].split(os.pathsep)

回答 3

PYTHONPATH是一个环境变量,其值是目录列表。设置后,Python将使用它与其他标准输入一起搜索导入的模块。和Python的“ sys.path”中列出的第三方库目录。

与其他任何环境变量一样,您可以将其导出到shell或〜/ .bashrc中,请参见此处。您可以在python中查询os.environ [‘PYTHONPATH’]的值,如下所示:

$ python3 -c "import os, sys; print(os.environ['PYTHONPATH']); print(sys.path) if 'PYTHONPATH' in sorted(os.environ) else print('PYTHONPATH is not defined')"

如果在shell中将IF定义为

$ export PYTHONPATH=$HOME/Documents/DjangoTutorial/mysite

然后结果=>

/home/Documents/DjangoTutorial/mysite
['', '/home/Documents/DjangoTutorial/mysite', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']

ELSE结果=>

PYTHONPATH is not defined

要将PYTHONPATH设置为多个路径,请参见此处

注意,可以在运行时通过sys.path.insert(),del或remove()添加或删除搜索路径,但不能通过os.environ []添加或删除搜索路径。例:

>>> os.environ['PYTHONPATH']="$HOME/Documents/DjangoTutorial/mysite"
>>> 'PYTHONPATH' in sorted(os.environ)
True
>>> sys.path // but Not there
['', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']

>>> sys.path.insert(0,os.environ['PYTHONPATH'])
>>> sys.path // It's there
['$HOME/Documents/DjangoTutorial/mysite', '', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']
>>> 

总之,PYTHONPATH是在sys.path中为导入的模块指定Python搜索路径的一种方法。您也可以不借助PYTHONPATH将列表操作直接应用于sys.path。

PYTHONPATH is an environment variable whose value is a list of directories. Once set, it is used by Python to search for imported modules, along with other std. and 3rd-party library directories listed in Python’s “sys.path”.

As any other environment variables, you can either export it in shell or in ~/.bashrc, see here. You can query os.environ[‘PYTHONPATH’] for its value in Python as shown below:

$ python3 -c "import os, sys; print(os.environ['PYTHONPATH']); print(sys.path) if 'PYTHONPATH' in sorted(os.environ) else print('PYTHONPATH is not defined')"

IF defined in shell as

$ export PYTHONPATH=$HOME/Documents/DjangoTutorial/mysite

THEN result =>

/home/Documents/DjangoTutorial/mysite
['', '/home/Documents/DjangoTutorial/mysite', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']

ELSE result =>

PYTHONPATH is not defined

To set PYTHONPATH to multiple paths, see here.

Note that one can add or delete a search path via sys.path.insert(), del or remove() at run-time, but NOT through os.environ[]. Example:

>>> os.environ['PYTHONPATH']="$HOME/Documents/DjangoTutorial/mysite"
>>> 'PYTHONPATH' in sorted(os.environ)
True
>>> sys.path // but Not there
['', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']

>>> sys.path.insert(0,os.environ['PYTHONPATH'])
>>> sys.path // It's there
['$HOME/Documents/DjangoTutorial/mysite', '', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']
>>> 

In summary, PYTHONPATH is one way of specifying the Python search path(s) for imported modules in sys.path. You can also apply list operations directly to sys.path without the aid of PYTHONPATH.


回答 4

当它给我一条错误消息时,Python告诉我它住在哪里:)

>>> import os
>>> os.environ['PYTHONPATH'].split(os.pathsep)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\martin\AppData\Local\Programs\Python\Python36-32\lib\os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'PYTHONPATH'
>>>

Python tells me where it lives when it gives me an error message :)

>>> import os
>>> os.environ['PYTHONPATH'].split(os.pathsep)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\martin\AppData\Local\Programs\Python\Python36-32\lib\os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'PYTHONPATH'
>>>

回答 5

用这个:

import sys
print(sys.executable)

或从cmd一行:

python -c "import sys; print(sys.executable)"

Use this:

import sys
print(sys.executable)

Or one line from the cmd:

python -c "import sys; print(sys.executable)"

将目录永久添加到PYTHONPATH?

问题:将目录永久添加到PYTHONPATH?

每当我使用时sys.path.append,都会添加新目录。但是,一旦我关闭python,列表将恢复为以前的值(默认值)。如何将目录永久添加到PYTHONPATH

Whenever I use sys.path.append, the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I permanently add a directory to PYTHONPATH?


回答 0

您需要将新目录添加到环境变量中PYTHONPATH,并用冒号与其之前的内容分隔开。在任何形式的Unix中,您都可以在启动脚本中执行此操作,该脚本适合于您正在使用的任何shell(.profile或取决于您喜欢的shell),该命令又取决于所讨论的shell。在Windows中,您可以为此目的通过系统GUI进行操作。

superuser.com 可能是一个更好的地方,例如,如果您需要有关如何在所选平台和外壳程序中丰富环境变量的详细信息,请提供更多详细信息,因为这本身并不是真正的编程问题。

You need to add your new directory to the environment variable PYTHONPATH, separated by a colon from previous contents thereof. In any form of Unix, you can do that in a startup script appropriate to whatever shell you’re using (.profile or whatever, depending on your favorite shell) with a command which, again, depends on the shell in question; in Windows, you can do it through the system GUI for the purpose.

superuser.com may be a better place to ask further, i.e. for more details if you need specifics about how to enrich an environment variable in your chosen platform and shell, since it’s not really a programming question per se.


回答 1

如果您正在使用bash(在Mac或GNU / Linux发行版上),请将其添加到您的 ~/.bashrc

export PYTHONPATH="${PYTHONPATH}:/my/other/path"

If you’re using bash (on a Mac or GNU/Linux distro), add this to your ~/.bashrc

export PYTHONPATH="${PYTHONPATH}:/my/other/path"

回答 2

除了操作之外,PYTHONPATH您还可以创建路径配置文件。首先找出Python在哪个目录中搜索此信息:

python -m site --user-site

由于某些原因,这似乎在Python 2.7中不起作用。在那里您可以使用:

python -c 'import site; site._script()' --user-site

然后.pth在该目录中创建一个文件,其中包含您要添加的路径(如果目录不存在,则创建该目录)。

例如:

# find directory
SITEDIR=$(python -m site --user-site)

# create if it doesn't exist
mkdir -p "$SITEDIR"

# create new .pth file with our path
echo "$HOME/foo/bar" > "$SITEDIR/somelib.pth"

Instead of manipulating PYTHONPATH you can also create a path configuration file. First find out in which directory Python searches for this information:

python -m site --user-site

For some reason this doesn’t seem to work in Python 2.7. There you can use:

python -c 'import site; site._script()' --user-site

Then create a .pth file in that directory containing the path you want to add (create the directory if it doesn’t exist).

For example:

# find directory
SITEDIR=$(python -m site --user-site)

# create if it doesn't exist
mkdir -p "$SITEDIR"

# create new .pth file with our path
echo "$HOME/foo/bar" > "$SITEDIR/somelib.pth"

回答 3

这适用于Windows

  1. 在Windows上,对于Python 2.7,请转到Python设置文件夹。
  2. 打开库/站点包。
  3. 将example.pth空文件添加到此文件夹。
  4. 将所需的路径添加到文件,每行一个。

然后,您将能够从脚本中查看这些路径内的所有模块。

This works on Windows

  1. On Windows, with Python 2.7 go to the Python setup folder.
  2. Open Lib/site-packages.
  3. Add an example.pth empty file to this folder.
  4. Add the required path to the file, one per each line.

Then you’ll be able to see all modules within those paths from your scripts.


回答 4

如果仍然有人困惑-如果您使用的是Mac,请执行以下操作:

  1. 打开终端
  2. 类型 open .bash_profile
  3. 在弹出的文本文件中,在最后添加以下行: export PYTHONPATH=$PYTHONPATH:foo/bar
  4. 保存文件,重新启动终端,然后完成

In case anyone is still confused – if you are on a Mac, do the following:

  1. Open up Terminal
  2. Type open .bash_profile
  3. In the text file that pops up, add this line at the end: export PYTHONPATH=$PYTHONPATH:foo/bar
  4. Save the file, restart the Terminal, and you’re done

回答 5

您可以通过pythonrc文件添加路径,该文件在Linux上默认为〜/ .pythonrc。即。

import sys
sys.path.append('/path/to/dir')

您也可以PYTHONPATH在全局rc文件中(例如~/.profile在Mac或Linux上)或通过Windows上的“控制面板”->“系统”->“高级”选项卡->“环境变量”来设置环境变量。

You could add the path via your pythonrc file, which defaults to ~/.pythonrc on linux. ie.

import sys
sys.path.append('/path/to/dir')

You could also set the PYTHONPATH environment variable, in a global rc file, such ~/.profile on mac or linux, or via Control Panel -> System -> Advanced tab -> Environment Variables on windows.


回答 6

为了提供更多说明,Python将使用脚本(通常位于sys.prefix + 和中)自动构建其搜索路径(如上所述此处)。一个可以获得sys.prefix的值:site.pylib/python<version>/site-packageslib/site-python

python -c 'import sys; print(sys.prefix)'

然后,site.py脚本将取决于平台的许多目录(例如/usr/{lib,share}/python<version>/dist-packages)添加/usr/local/lib/python<version>/dist-packages到搜索路径,并且还在这些路径中<package>.pth搜索包含特定其他搜索路径的配置文件。例如,easy-install维护其已安装软件包的集合,这些软件包已添加到系统特定文件中,例如在Ubuntu上/usr/local/lib/python2.7/dist-packages/easy-install.pth。在典型的系统上,有很多这些.pth文件,它们可以解释sys.path中一些意外的路径:

python -c 'import sys; print(sys.path)'

因此,可以创建一个.pth文件并将其放置在任何这些目录中(包括如上所述的sitedir )。这似乎是大多数软件包被添加到sys.path的方式,而不是使用PYTHONPATH。

注意:在OSX上,site.py为’framework builds’添加了一个特殊的附加搜索路径(但似乎适用于python的常规命令行使用):(/Library/Python/<version>/site-packages例如,对于Python2.7:)/Library/Python/2.7/site-packages/,这是应该使用第三方软件包的地方要安装(请参阅该目录中的自述文件)。因此,可以在其中添加包含其他搜索路径的路径配置文件,例如创建一个名为的文件/Library/Python/2.7/site-packages/pip-usr-local.pth,其中包含/usr/local/lib/python2.7/site-packages/,然后系统python将添加该搜索路径。

To give a bit more explanation, Python will automatically construct its search paths (as mentioned above and here) using the site.py script (typically located in sys.prefix + lib/python<version>/site-packages as well as lib/site-python). One can obtain the value of sys.prefix:

python -c 'import sys; print(sys.prefix)'

The site.py script then adds a number of directories, dependent upon the platform, such as /usr/{lib,share}/python<version>/dist-packages, /usr/local/lib/python<version>/dist-packages to the search path and also searches these paths for <package>.pth config files which contain specific additional search paths. For example easy-install maintains its collection of installed packages which are added to a system specific file e.g on Ubuntu it’s /usr/local/lib/python2.7/dist-packages/easy-install.pth. On a typical system there are a bunch of these .pth files around which can explain some unexpected paths in sys.path:

python -c 'import sys; print(sys.path)'

So one can create a .pth file and put in any of these directories (including the sitedir as mentioned above). This seems to be the way most packages get added to the sys.path as opposed to using the PYTHONPATH.

Note: On OSX there’s a special additional search path added by site.py for ‘framework builds’ (but seems to work for normal command line use of python): /Library/Python/<version>/site-packages (e.g. for Python2.7: /Library/Python/2.7/site-packages/) which is where 3rd party packages are supposed to be installed (see the README in that dir). So one can add a path configuration file in there containing additional search paths e.g. create a file called /Library/Python/2.7/site-packages/pip-usr-local.pth which contains /usr/local/lib/python2.7/site-packages/ and then the system python will add that search path.


回答 7

对我来说,当我更改.bash_profile文件时它起作用了。只是更改.bashrc文件才有效,直到我重新启动外壳程序为止。

对于python 2.7,它应如下所示:

export PYTHONPATH="$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python"

.bash_profile文件末尾。

For me it worked when I changed the .bash_profile file. Just changing .bashrc file worked only till I restarted the shell.

For python 2.7 it should look like:

export PYTHONPATH="$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python"

at the end of the .bash_profile file.


回答 8

在Linux上,您可以创建从软件包到PYTHONPATH目录的符号链接,而不必处理环境变量。就像是:

ln -s /your/path /usr/lib/pymodules/python2.7/

On linux you can create a symbolic link from your package to a directory of the PYTHONPATH without having to deal with the environment variables. Something like:

ln -s /your/path /usr/lib/pymodules/python2.7/

回答 9

export PYTHONPATH="${PYTHONPATH}:/my/other/path"如果PYTHONPATH当前不存在,则添加到〜/ .bashrc可能不起作用(因为:)。

export PYTHONPATH="/my/other/path1"
export PYTHONPATH="${PYTHONPATH}:/my/other/path2"

将以上内容添加到我的〜/ .bashrc中可以在Ubuntu 16.04上为我实现窍门

Adding export PYTHONPATH="${PYTHONPATH}:/my/other/path" to the ~/.bashrc might not work if PYTHONPATH does not currently exist (because of the :).

export PYTHONPATH="/my/other/path1"
export PYTHONPATH="${PYTHONPATH}:/my/other/path2"

Adding the above to my ~/.bashrc did the trick for me on Ubuntu 16.04


回答 10

在MacOS上,而不是提供到特定库的路径。提供到根项目文件夹的完整路径

~/.bash_profile 

让我过得愉快,例如:

export PYTHONPATH="${PYTHONPATH}:/Users/<myuser>/project_root_folder_path"

在此之后:

source ~/.bash_profile

On MacOS, Instead of giving path to a specific library. Giving full path to the root project folder in

~/.bash_profile 

made my day, for example:

export PYTHONPATH="${PYTHONPATH}:/Users/<myuser>/project_root_folder_path"

after this do:

source ~/.bash_profile

回答 11

只是对awesomo的答案添加,也可以添加该行到您~/.bash_profile~/.profile

Just to add on awesomo’s answer, you can also add that line into your ~/.bash_profile or ~/.profile


回答 12

通过以下方式手动添加到PYTHONPATH的新路径:

在终端中通过以下方式将路径添加到〜/ .bashrc配置文件中:

vim ~/.bashrc

将以下内容粘贴到您的个人资料中

export PYTHONPATH="${PYTHONPATH}:/User/johndoe/pythonModule"

然后,确保在终端中运行代码时都获取bashrc配置文件的来源:

source ~/.bashrc 

希望这可以帮助。

The add a new path to PYTHONPATH is doing in manually by:

adding the path to your ~/.bashrc profile, in terminal by:

vim ~/.bashrc

paste the following to your profile

export PYTHONPATH="${PYTHONPATH}:/User/johndoe/pythonModule"

then, make sure to source your bashrc profile when ever you run your code in terminal:

source ~/.bashrc 

Hope this helps.


回答 13

我在Windows Vista中永久添加了Python 3.5

系统>控制面板>高级系统设置>高级(点击)环境变量>系统变量>(如果在“变量”列中没有看到PYTHONPATH)(单击)新建>变量名称:PYTHONPATH>变量值:

请在变量值中写入目录。这是Blue Peppers答案的细节。

I added permanently in Windows Vista, Python 3.5

System > Control Panel > Advanced system settings > Advanced (tap) Environment Variables > System variables > (if you don’t see PYTHONPATH in Variable column) (click) New > Variable name: PYTHONPATH > Variable value:

Please, write the directory in the Variable value. It is details of Blue Peppers’ answer.


回答 14

以下脚本是纯Python,因此可在所有平台上使用。它利用了https://docs.python.org/3/library/pathlib.html此处记录的pathlib路径,以使其跨平台工作。您只需运行一次,然后重新启动内核即可。受https://medium.com/@arnaud.bertrand/modifying-python-s-search-path-with-pth-files-2a41a4143574的启发。

from pathlib import Path
to_add=Path(path_of_directory_to_add)
from sys import path

if str(to_add) not in path:
    minLen=999999
    for index,directory in enumerate(path):
        if 'site-packages' in directory and len(directory)<=minLen:
            minLen=len(directory)
            stpi=index

    pathSitePckgs=Path(path[stpi])
    with open(str(pathSitePckgs/'current_machine_paths.pth'),'w') as pth_file:
        pth_file.write(str(to_add))

The script below works on all platforms as it’s pure Python. It makes use of the pathlib Path, documented here https://docs.python.org/3/library/pathlib.html, to make it work cross-platform. You run it once, restart the kernel and that’s it. Inspired by https://medium.com/@arnaud.bertrand/modifying-python-s-search-path-with-pth-files-2a41a4143574.

from pathlib import Path
to_add=Path(path_of_directory_to_add)
from sys import path

if str(to_add) not in path:
    minLen=999999
    for index,directory in enumerate(path):
        if 'site-packages' in directory and len(directory)<=minLen:
            minLen=len(directory)
            stpi=index

    pathSitePckgs=Path(path[stpi])
    with open(str(pathSitePckgs/'current_machine_paths.pth'),'w') as pth_file:
        pth_file.write(str(to_add))

回答 15

这是对此线程的更新,具有一些旧的答案。

对于使用MAC-OS Catalina或更高版本(> = 10.15)的用户,它引入了一个新的终端,名为zsh(替代旧的bash)。

由于此更改,上述答案有些问题,我通过创建文件~/.zshrc并将文件目录粘贴到$PATH和进行了一些变通方法$PYTHONPATH

所以,首先我做了:

nano ~/.zshrc

当编辑器打开时,我粘贴了以下内容:

export PATH="${PATH}:/Users/caio.hc.oliveira/Library/Python/3.7/bin"
export PYTHONPATH="${PYTHONPATH}:/Users/caio.hc.oliveira/Library/Python/3.7/bin"

保存它,然后重新启动终端。

重要提示:上面的路径设置为我计算机的路径,您必须将其调整为适合您的python。

This is an update to this thread which has some old answers.

For those using MAC-OS Catalina or some newer (>= 10.15), it was introduced a new Terminal named zsh (a substitute to the old bash).

I had some problems with the answers above due to this change, and I somewhat did a workaround by creating the file ~/.zshrc and pasting the file directory to the $PATH and $PYTHONPATH

So, first I did:

nano ~/.zshrc

When the editor opened I pasted the following content:

export PATH="${PATH}:/Users/caio.hc.oliveira/Library/Python/3.7/bin"
export PYTHONPATH="${PYTHONPATH}:/Users/caio.hc.oliveira/Library/Python/3.7/bin"

saved it, and restarted the terminal.

IMPORTANT: The path above is set to my computer’s path, you would have to adapt it to your python.


回答 16

在Python 3.6.4中,您可以像这样在python会话之间持久化sys.path:

import sys
import os

print(str(sys.path))

dir_path = os.path.dirname(os.path.realpath(__file__))
print(f"current working dir: {dir_path}")

root_dir = dir_path.replace("/util", '', 1)
print(f"root dir: {root_dir}")

sys.path.insert(0, root_dir)

print(str(sys.path))

我强烈建议您使用virtualenv和virtualenvwrapper,否则您的路径将会混乱

In Python 3.6.4 you can persist sys.path across python sessions like this:

import sys
import os

print(str(sys.path))

dir_path = os.path.dirname(os.path.realpath(__file__))
print(f"current working dir: {dir_path}")

root_dir = dir_path.replace("/util", '', 1)
print(f"root dir: {root_dir}")

sys.path.insert(0, root_dir)

print(str(sys.path))

I strongly suggest you use virtualenv and virtualenvwrapper otherwise you will clutter your path


回答 17

A <-> B之间的最短路径是一条直线;

import sys
if not 'NEW_PATH' in sys.path:
  sys.path += ['NEW_PATH']

Shortest path between A <-> B is a straight line;

import sys
if not 'NEW_PATH' in sys.path:
  sys.path += ['NEW_PATH']