标签归档:module

列出所有属于python软件包的模块吗?

问题:列出所有属于python软件包的模块吗?

有没有一种直接的方法来查找python软件包中的所有模块?我已经找到了这个旧的讨论,这并不是真正的结论,但是我很想在我基于os.listdir()推出自己的解决方案之前有一个明确的答案。

Is there a straightforward way to find all the modules that are part of a python package? I’ve found this old discussion, which is not really conclusive, but I’d love to have a definite answer before I roll out my own solution based on os.listdir().


回答 0

是的,您需要某种基于pkgutil或相似的东西-这样,您可以将所有软件包都视为相同,而不管它们是放在鸡蛋还是拉链中(在os.listdir都不起作用的地方)。

import pkgutil

# this is the package we are inspecting -- for example 'email' from stdlib
import email

package = email
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__):
    print "Found submodule %s (is a package: %s)" % (modname, ispkg)

如何导入它们呢?您可以__import__照常使用:

import pkgutil

# this is the package we are inspecting -- for example 'email' from stdlib
import email

package = email
prefix = package.__name__ + "."
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__, prefix):
    print "Found submodule %s (is a package: %s)" % (modname, ispkg)
    module = __import__(modname, fromlist="dummy")
    print "Imported", module

Yes, you want something based on pkgutil or similar — this way you can treat all packages alike regardless if they are in eggs or zips or so (where os.listdir won’t help).

import pkgutil

# this is the package we are inspecting -- for example 'email' from stdlib
import email

package = email
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__):
    print "Found submodule %s (is a package: %s)" % (modname, ispkg)

How to import them too? You can just use __import__ as normal:

import pkgutil

# this is the package we are inspecting -- for example 'email' from stdlib
import email

package = email
prefix = package.__name__ + "."
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__, prefix):
    print "Found submodule %s (is a package: %s)" % (modname, ispkg)
    module = __import__(modname, fromlist="dummy")
    print "Imported", module

回答 1

这项工作的正确工具是pkgutil.walk_packages。

要列出系统上的所有模块:

import pkgutil
for importer, modname, ispkg in pkgutil.walk_packages(path=None, onerror=lambda x: None):
    print(modname)

请注意,walk_packages会导入所有子包,但不会导入子模块。

如果您希望列出某个程序包的所有子模块,则可以使用如下代码:

import pkgutil
import scipy
package=scipy
for importer, modname, ispkg in pkgutil.walk_packages(path=package.__path__,
                                                      prefix=package.__name__+'.',
                                                      onerror=lambda x: None):
    print(modname)

iter_modules仅列出一级深度的模块。walk_packages获取所有子模块。例如,对于scipy,walk_packages返回

scipy.stats.stats

而iter_modules仅返回

scipy.stats

pkgutil的文档(http://docs.python.org/library/pkgutil.html)没有列出/usr/lib/python2.6/pkgutil.py中定义的所有有趣功能。

也许这意味着功能不是“公共”界面的一部分,并且可能会发生变化。

但是,至少从Python 2.6起(也许是早期版本?),pkgutil带有walk_packages方法,该方法递归地遍历所有可用模块。

The right tool for this job is pkgutil.walk_packages.

To list all the modules on your system:

import pkgutil
for importer, modname, ispkg in pkgutil.walk_packages(path=None, onerror=lambda x: None):
    print(modname)

Be aware that walk_packages imports all subpackages, but not submodules.

If you wish to list all submodules of a certain package then you can use something like this:

import pkgutil
import scipy
package=scipy
for importer, modname, ispkg in pkgutil.walk_packages(path=package.__path__,
                                                      prefix=package.__name__+'.',
                                                      onerror=lambda x: None):
    print(modname)

iter_modules only lists the modules which are one-level deep. walk_packages gets all the submodules. In the case of scipy, for example, walk_packages returns

scipy.stats.stats

while iter_modules only returns

scipy.stats

The documentation on pkgutil (http://docs.python.org/library/pkgutil.html) does not list all the interesting functions defined in /usr/lib/python2.6/pkgutil.py.

Perhaps this means the functions are not part of the “public” interface and are subject to change.

However, at least as of Python 2.6 (and perhaps earlier versions?) pkgutil comes with a walk_packages method which recursively walks through all the modules available.


回答 2

这对我有用:

import types

for key, obj in nltk.__dict__.iteritems():
    if type(obj) is types.ModuleType: 
        print key

This works for me:

import types

for key, obj in nltk.__dict__.iteritems():
    if type(obj) is types.ModuleType: 
        print key

回答 3

我一直在寻找一种方法来重新加载我正在编辑的程序包中的所有子模块。它是上述答案/评论的组合,因此我决定将其发布在此处,作为答案而不是评论。

package=yourPackageName
import importlib
import pkgutil
for importer, modname, ispkg in pkgutil.walk_packages(path=package.__path__, prefix=package.__name__+'.', onerror=lambda x: None):
    try:
        modulesource = importlib.import_module(modname)
        reload(modulesource)
        print("reloaded: {}".format(modname))
    except Exception as e:
        print('Could not load {} {}'.format(modname, e))

I was looking for a way to reload all submodules that I’m editing live in my package. It is a combination of the answers/comments above, so I’ve decided to post it here as an answer rather than a comment.

package=yourPackageName
import importlib
import pkgutil
for importer, modname, ispkg in pkgutil.walk_packages(path=package.__path__, prefix=package.__name__+'.', onerror=lambda x: None):
    try:
        modulesource = importlib.import_module(modname)
        reload(modulesource)
        print("reloaded: {}".format(modname))
    except Exception as e:
        print('Could not load {} {}'.format(modname, e))

回答 4

这是我的头上的一种方法:

>>> import os
>>> filter(lambda i: type(i) == type(os), [getattr(os, j) for j in dir(os)])
[<module 'UserDict' from '/usr/lib/python2.5/UserDict.pyc'>, <module 'copy_reg' from '/usr/lib/python2.5/copy_reg.pyc'>, <module 'errno' (built-in)>, <module 'posixpath' from '/usr/lib/python2.5/posixpath.pyc'>, <module 'sys' (built-in)>]

它肯定可以清理和改进。

编辑:这是一个稍微更好的版本:

>>> [m[1] for m in filter(lambda a: type(a[1]) == type(os), os.__dict__.items())]
[<module 'copy_reg' from '/usr/lib/python2.5/copy_reg.pyc'>, <module 'UserDict' from '/usr/lib/python2.5/UserDict.pyc'>, <module 'posixpath' from '/usr/lib/python2.5/posixpath.pyc'>, <module 'errno' (built-in)>, <module 'sys' (built-in)>]
>>> [m[0] for m in filter(lambda a: type(a[1]) == type(os), os.__dict__.items())]
['_copy_reg', 'UserDict', 'path', 'errno', 'sys']

注意:如果将模块拉入__init__.py文件中,它们也将找到不一定位于包子目录中的模块,因此取决于您“包的一部分”的含义。

Here’s one way, off the top of my head:

>>> import os
>>> filter(lambda i: type(i) == type(os), [getattr(os, j) for j in dir(os)])
[<module 'UserDict' from '/usr/lib/python2.5/UserDict.pyc'>, <module 'copy_reg' from '/usr/lib/python2.5/copy_reg.pyc'>, <module 'errno' (built-in)>, <module 'posixpath' from '/usr/lib/python2.5/posixpath.pyc'>, <module 'sys' (built-in)>]

It could certainly be cleaned up and improved.

EDIT: Here’s a slightly nicer version:

>>> [m[1] for m in filter(lambda a: type(a[1]) == type(os), os.__dict__.items())]
[<module 'copy_reg' from '/usr/lib/python2.5/copy_reg.pyc'>, <module 'UserDict' from '/usr/lib/python2.5/UserDict.pyc'>, <module 'posixpath' from '/usr/lib/python2.5/posixpath.pyc'>, <module 'errno' (built-in)>, <module 'sys' (built-in)>]
>>> [m[0] for m in filter(lambda a: type(a[1]) == type(os), os.__dict__.items())]
['_copy_reg', 'UserDict', 'path', 'errno', 'sys']

NOTE: This will also find modules that might not necessarily be located in a subdirectory of the package, if they’re pulled in in its __init__.py file, so it depends on what you mean by “part of” a package.


如何从另一个模块更改模块变量?

问题:如何从另一个模块更改模块变量?

假设我有一个名为的软件包bar,其中包含bar.py

a = None

def foobar():
    print a

__init__.py

from bar import a, foobar

然后我执行以下脚本:

import bar

print bar.a
bar.a = 1
print bar.a
bar.foobar()

这是我的期望:

None
1
1

这是我得到的:

None
1
None

谁能解释我的误解?

Suppose I have a package named bar, and it contains bar.py:

a = None

def foobar():
    print a

and __init__.py:

from bar import a, foobar

Then I execute this script:

import bar

print bar.a
bar.a = 1
print bar.a
bar.foobar()

Here’s what I expect:

None
1
1

Here’s what I get:

None
1
None

Can anyone explain my misconception?


回答 0

您正在使用from bar import aa在导入模块的全局范围(或​​发生import语句的任何范围)中成为符号。

当您为指定新值时a,您也只是在更改哪些值a,而不是实际值。尝试bar.py直接使用import barin 导入,__init__.py并通过设置在那里进行实验bar.a = 1。这样,您实际上将在此上下文中修改bar.__dict__['a']哪个是“实际”值a

它有点复杂,分为三层,但是bar.a = 1更改了实际上是从派生a的模块中的值。它不会更改所看到的值,因为它存在于实际文件中。您可以设置是否要更改它。bar__init__.pyafoobarfoobarbar.pybar.bar.a

这是使用语句from foo import bar形式的危险之一import:它将分成bar两个符号,一个符号在全局范围内可见,从foo该符号开始指向原始值,而另一个符号在import执行该语句的范围内可见。更改符号指向的位置也不会更改其指向的值。

尝试reload从交互式解释器访问模块时,这种东西是致命的。

You are using from bar import a. a becomes a symbol in the global scope of the importing module (or whatever scope the import statement occurs in).

When you assign a new value to a, you are just changing which value a points too, not the actual value. Try to import bar.py directly with import bar in __init__.py and conduct your experiment there by setting bar.a = 1. This way, you will actually be modifying bar.__dict__['a'] which is the ‘real’ value of a in this context.

It’s a little convoluted with three layers but bar.a = 1 changes the value of a in the module called bar that is actually derived from __init__.py. It does not change the value of a that foobar sees because foobar lives in the actual file bar.py. You could set bar.bar.a if you wanted to change that.

This is one of the dangers of using the from foo import bar form of the import statement: it splits bar into two symbols, one visible globally from within foo which starts off pointing to the original value and a different symbol visible in the scope where the import statement is executed. Changing a where a symbol points doesn’t change the value that it pointed too.

This sort of stuff is a killer when trying to reload a module from the interactive interpreter.


回答 1

这个问题困难的一个原因是,你有一个名为程序bar/bar.pyimport bar可导入bar/__init__.pybar/bar.py,取决于它完成,这使得它有点笨重跟踪哪些abar.a

下面是它的工作原理:

了解发生了什么事情的关键是要意识到自己__init__.py

from bar import a

实际上做了类似的事情

a = bar.a
# … where bar = bar/bar.py (as if bar were imported locally from __init__.py)

并定义一个新变量(bar/__init__.py:a,如果需要的话)。因此,您的from bar import ain __init__.py会将名称绑定bar/__init__.py:a到原始bar.py:a对象(None)。这就是为什么你可以做from bar import a as a2__init__.py:在这种情况下,很显然,你有两个bar/bar.py:a和一个不同的变量名bar/__init__.py:a2(在你的情况下,这两个变量的名字恰好两者a,但他们仍然生活在不同的命名空间:在__init__.py,它们是bar.aa)。

现在,当你做

import bar

print bar.a

您正在访问变量bar/__init__.py:a(因为import bar导入了your bar/__init__.py)。这是您修改的变量(为1)。您没有触及variable的内容bar/bar.py:a。所以当你随后做

bar.foobar()

您调用bar/bar.py:foobar(),它将访问a来自的变量bar/bar.py,后者仍然是Nonefoobar()定义后,它将一劳永逸地绑定变量名称,因此ain bar.pybar.py:a,而不是a另一个模块中定义的任何其他变量-因为a在所有导入的模块中可能有很多变量)。因此是最后一个None输出。

结论:最好是避免任何含糊之处import bar,由具有任何bar/bar.py模块(因为bar.__init__.py品牌目录bar/包已经,您还可以导入import bar)。

One source of difficulty with this question is that you have a program named bar/bar.py: import bar imports either bar/__init__.py or bar/bar.py, depending on where it is done, which makes it a little cumbersome to track which a is bar.a.

Here is how it works:

The key to understanding what happens is to realize that in your __init__.py,

from bar import a

in effect does something like

a = bar.a
# … where bar = bar/bar.py (as if bar were imported locally from __init__.py)

and defines a new variable (bar/__init__.py:a, if you wish). Thus, your from bar import a in __init__.py binds name bar/__init__.py:a to the original bar.py:a object (None). This is why you can do from bar import a as a2 in __init__.py: in this case, it is clear that you have both bar/bar.py:a and a distinct variable name bar/__init__.py:a2 (in your case, the names of the two variables just happen to both be a, but they still live in different namespaces: in __init__.py, they are bar.a and a).

Now, when you do

import bar

print bar.a

you are accessing variable bar/__init__.py:a (since import bar imports your bar/__init__.py). This is the variable you modify (to 1). You are not touching the contents of variable bar/bar.py:a. So when you subsequently do

bar.foobar()

you call bar/bar.py:foobar(), which accesses variable a from bar/bar.py, which is still None (when foobar() is defined, it binds variable names once and for all, so the a in bar.py is bar.py:a, not any other a variable defined in another module—as there might be many a variables in all the imported modules). Hence the last None output.

Conclusion: it is best to avoid any ambiguity in import bar, by not having any bar/bar.py module (since bar.__init__.py makes directory bar/ a package already, that you can also import with import bar).


回答 2

换一种说法:事实证明,这种误解很容易造成。 它是在Python语言参考中偷偷地定义的:使用object而不是symbol。我建议使用Python语言参考使这一点更清晰,更稀疏。

from形式不结合模块名称:它通过标识符的列表,看起来它们中的每一个向上的模块中,在步骤(1)中发现,并结合在本地命名空间中的名称对象从而找到。

然而:

导入时,将导入已导入符号的当前值,并将其添加到已定义的命名空间中。 您不是在导入参考,而是在有效导入值。

因此,要获取的更新值i,必须导入一个变量,该变量包含对该符号的引用。

换句话说,导入import与JAVA中的,externalC / C ++中的声明甚use至PERL中的子句都不一样。

而是在Python中执行以下语句:

from some_other_module import a as x

是更喜欢在K&R C下面的代码:

extern int a; /* import from the EXTERN file */

int x = a;

(注意:在Python情况下,“ a”和“ x”本质上是对实际值的引用:您不是在复制INT,而是在复制引用地址)

To put another way: Turns out this misconception is very easy to make. It is sneakily defined in the Python language reference: the use of object instead of symbol. I would suggest that the Python language reference make this more clear and less sparse..

The from form does not bind the module name: it goes through the list of identifiers, looks each one of them up in the module found in step (1), and binds the name in the local namespace to the object thus found.

HOWEVER:

When you import, you import the current value of the imported symbol and add it to your namespace as defined. You are not importing a reference, you are effectively importing a value.

Thus, to get the updated value of i, you must import a variable that holds a reference to that symbol.

In other words, importing is NOT like an import in JAVA, external declaration in C/C++ or even a use clause in PERL.

Rather, the following statement in Python:

from some_other_module import a as x

is more like the following code in K&R C:

extern int a; /* import from the EXTERN file */

int x = a;

(caveat: in the Python case, “a” and “x” are essentially a reference to the actual value: you’re not copying the INT, you’re copying the reference address)


从子文件夹导入模块

问题:从子文件夹导入模块

我想将子文件夹作为模块导入。因此,每个子文件夹都包含一个__init__.py。我的文件夹结构是这样的:

src\
  main.py
  dirFoo\
    __init__.py
    foofactory.py
    dirFoo1\
      __init__.py
      foo1.py
    dirFoo2\
      __init__.py
      foo2.py

在我的主脚本中,导入

from dirFoo.foofactory import FooFactory

在此工厂文件中,我包括以下子模块:

from dirFoo1.foo1 import Foo1
from dirFoo2.foo2 import Foo2

如果我叫我的foofactory我得到了错误,那说明python无法导入子模块foo1和foo2:

Traceback (most recent call last):
  File "/Users/tmp/src/main.py", line 1, in <module>
from dirFoo.foofactory import FooFactory
  File "/Users/tmp/src/dirFoo/foofactory.py", line 1, in    <module>
from dirFoo1.foo1 import Foo1
    ImportError: No module named dirFoo1.foo1

I want to import subfolders as modules. Therefore every subfolder contains a __init__.py. My folder structure is like this:

src\
  main.py
  dirFoo\
    __init__.py
    foofactory.py
    dirFoo1\
      __init__.py
      foo1.py
    dirFoo2\
      __init__.py
      foo2.py

In my main script I import

from dirFoo.foofactory import FooFactory

In this factory file I include the sub modules:

from dirFoo1.foo1 import Foo1
from dirFoo2.foo2 import Foo2

If I call my foofactory I get the error, that python can’t import the submodules foo1 and foo2:

Traceback (most recent call last):
  File "/Users/tmp/src/main.py", line 1, in <module>
from dirFoo.foofactory import FooFactory
  File "/Users/tmp/src/dirFoo/foofactory.py", line 1, in    <module>
from dirFoo1.foo1 import Foo1
    ImportError: No module named dirFoo1.foo1

回答 0

无需与您PYTHONPATHsys.path此处混淆。

为了在包中正确使用绝对导入,还应该包括“ root”包名,例如:

from dirFoo.dirFoo1.foo1 import Foo1
from dirFoo.dirFoo2.foo2 import Foo2

或者您可以使用相对导入

from .dirfoo1.foo1 import Foo1
from .dirfoo2.foo2 import Foo2

There’s no need to mess with your PYTHONPATH or sys.path here.

To properly use absolute imports in a package you should include the “root” packagename as well, e.g.:

from dirFoo.dirFoo1.foo1 import Foo1
from dirFoo.dirFoo2.foo2 import Foo2

Or you can use relative imports:

from .dirfoo1.foo1 import Foo1
from .dirfoo2.foo2 import Foo2

回答 1

只是在这里通知。(来自新蜜蜂keviv22)

永远不要为了自己的利益而用“-”或“ _”之类的符号命名文件夹或文件。如果这样做,您可能会遇到一些问题。就像我的一样,尽管导入命令正确无误,但您将无法成功导入所需的文件,这些文件在此类命名文件夹中可用。

无效的文件夹命名如下:

  • 通用类文件夹
  • Generic_Classes_Folder

上面的有效文件夹命名:

  • GenericClassesFolder或Genericclassesfolder或genericClassesFolder(或类似的词,单词之间没有任何空格或特殊符号)

我犯了什么错误:

考虑文件结构。

Parent
   . __init__.py
   . Setup
     .. __init__.py
     .. Generic-Class-Folder
        ... __init__.py
        ... targetClass.py
   . Check
     .. __init__.py
     .. testFile.py

我想做什么?

  • 从testFile.py,我想在Generic-Class-Folder文件中导入“ targetClass.py”文件,以在“ targetClass.py”文件中使用名为“ functionExecute”的函数

我做了什么命令?

  • 来自“ testFile.py”,写了命令, from Core.Generic-Class-Folder.targetClass import functionExecute
  • 有类似的错误 SyntaxError: invalid syntax

尝试了许多搜索并查看了许多stackoverflow问题,但无法确定出了什么问题。我多次交叉检查文件,使用__init__.py文件,插入环境路径,非常担心出了什么问题……

在很长很长一段时间后,我在和我的一个朋友交谈时想出了这一点。使用这样的命名约定我并不傻。我绝对不要使用空格或特殊符号为任何文件夹或文件定义名称。所以,这就是我想传达的。祝你有美好的一天!

(很抱歉在此发布大量文章……只是让我的挫败感….::)谢谢!)

Just to notify here. (from a newbee, keviv22)

Never and ever for the sake of your own good, name the folders or files with symbols like “-” or “_”. If you did so, you may face few issues. like mine, say, though your command for importing is correct, you wont be able to successfully import the desired files which are available inside such named folders.

Invalid Folder namings as follows:

  • Generic-Classes-Folder
  • Generic_Classes_Folder

valid Folder namings for above:

  • GenericClassesFolder or Genericclassesfolder or genericClassesFolder (or like this without any spaces or special symbols among the words)

What mistake I did:

consider the file structure.

Parent
   . __init__.py
   . Setup
     .. __init__.py
     .. Generic-Class-Folder
        ... __init__.py
        ... targetClass.py
   . Check
     .. __init__.py
     .. testFile.py

What I wanted to do?

  • from testFile.py, I wanted to import the ‘targetClass.py’ file inside the Generic-Class-Folder file to use the function named “functionExecute” in ‘targetClass.py’ file

What command I did?

  • from ‘testFile.py’, wrote command, from Core.Generic-Class-Folder.targetClass import functionExecute
  • Got errors like SyntaxError: invalid syntax

Tried many searches and viewed many stackoverflow questions and unable to decide what went wrong. I cross checked my files multiple times, i used __init__.py file, inserted environment path and hugely worried what went wrong……

And after a long long long time, i figured this out while talking with a friend of mine. I am little stupid to use such naming conventions. I should never use space or special symbols to define a name for any folder or file. So, this is what I wanted to convey. Have a good day!

(sorry for the huge post over this… just letting my frustrations go…. :) Thanks!)


回答 2

设置您的PYTHONPATH环境变量。例如这样的PYTHONPATH =。:..(对于* nix系列)。

您也可以手动将当前目录(在您的情况下为src)添加到pythonpath中:

import os
import sys
sys.path.insert(0, os.getcwd())

Set your PYTHONPATH environment variable. For example like this PYTHONPATH=.:.. (for *nix family).

Also you can manually add your current directory (src in your case) to pythonpath:

import os
import sys
sys.path.insert(0, os.getcwd())

回答 3

假设您的项目采用以下结构:

+---MyPythonProject
|   +---.gitignore
|   +---run.py
|   |   +---subscripts
|   |   |   +---script_one.py
|   |   |   +---script_two.py

run.py,您可以通过以下方式导入脚本一和二:

from subscripts import script_one as One
from subscripts import script_two as Two

现在,仍然在内run.py,您可以使用以下命令调用其方法:

One.method_from_one(param)
Two.method_from_two(other_param)

Say your project is structured this way:

+---MyPythonProject
|   +---.gitignore
|   +---run.py
|   |   +---subscripts
|   |   |   +---script_one.py
|   |   |   +---script_two.py

Inside run.py, you can import scripts one and two by:

from subscripts import script_one as One
from subscripts import script_two as Two

Now, still inside run.py, you’ll be able to call their methods with:

One.method_from_one(param)
Two.method_from_two(other_param)

回答 4

只需创建一个空的____init____.py文件,并将其添加到root以及您拥有其他python模块的python应用程序的所有子目录/文件夹中即可。

Just create an empty __init__.py file and add it in root as well as all the sub directory/folder of your python application where you have other python modules. See https://docs.python.org/3/tutorial/modules.html#packages


回答 5

即使子文件夹中存在init .py且在导入后添加“ as” 时仍存在问题

from folder.file import Class as Class
import folder.file as functions

Had problems even when init.py existed in subfolder and all that was missing was adding ‘as’ after import

from folder.file import Class as Class
import folder.file as functions

ImportError:没有名为六个模块

问题:ImportError:没有名为六个模块

我正在尝试构建OpenERP项目,并完成了依赖项。现在出现此错误

Traceback (most recent call last):
  File "openerp-client.py", line 105, in <module>
  File "modules\__init__.pyo", line 23, in <module>
  File "modules\gui\__init__.pyo", line 22, in <module>
  File "modules\gui\main.pyo", line 33, in <module>
  File "rpc.pyo", line 29, in <module>
  File "common\__init__.pyo", line 22, in <module>
  File "common\common.pyo", line 26, in <module>
  File "tools\__init__.pyo", line 28, in <module>
  File "dateutil\relativedelta.pyo", line 12, in <module>
ImportError: No module named six

有人可以指导出什么问题以及如何解决吗???

I’m trying to build OpenERP project, done with dependencies. It’s giving this error now

Traceback (most recent call last):
  File "openerp-client.py", line 105, in <module>
  File "modules\__init__.pyo", line 23, in <module>
  File "modules\gui\__init__.pyo", line 22, in <module>
  File "modules\gui\main.pyo", line 33, in <module>
  File "rpc.pyo", line 29, in <module>
  File "common\__init__.pyo", line 22, in <module>
  File "common\common.pyo", line 26, in <module>
  File "tools\__init__.pyo", line 28, in <module>
  File "dateutil\relativedelta.pyo", line 12, in <module>
ImportError: No module named six

Could someone guide what’s wrong and how it can be fixed???


回答 0

您可能没有six安装Python模块。您可以在pypi上找到它。

要安装它:

$ easy_install six

(如果已pip安装,请pip install six改用)

You probably don’t have the six Python module installed. You can find it on pypi.

To install it:

$ easy_install six

(if you have pip installed, use pip install six instead)


回答 1

如果pip“说”了六个,但您仍然得到:

ImportError: No module named six.moves

尝试重新安装六个(为我工作):

pip uninstall six
pip install six

If pip “says” six is installed but you’re still getting:

ImportError: No module named six.moves

try re-installing six (worked for me):

pip uninstall six
pip install six

回答 2

在Ubuntu和Debian上

apt-get install python-six

绝招。

使用sudo apt-get install python-six,如果你得到一个错误说“权限被拒绝”。

On Ubuntu and Debian

apt-get install python-six

does the trick.

Use sudo apt-get install python-six if you get an error saying “permission denied”.


回答 3

对于Mac OS X:

pip install --ignore-installed six

For Mac OS X:

pip install --ignore-installed six

回答 4

我做了以下工作来解决上述问题。我尝试运行内置的exe时遇到了上述问题,即使我使用pyinstaller成功构建了exe。我是在Windows 10上完成的。

  1. 转到https://pypi.org/project/six/#files
  2. 下载“ six-1.14.0.tar.gz(33.9 kB)”
  3. 解压缩它,将“ six.py”复制并粘贴到您的源目录中。
  4. 将“六个”模块导入您的源代码(导入六个)
  5. 运行源脚本。

I did the following to solve the mentioned problem. I got the mentioned problem when I was trying to run the built exe, even I successfully built the exe using pyinstaller. I did this on Windows 10.

  1. go to https://pypi.org/project/six/#files
  2. download “six-1.14.0.tar.gz (33.9 kB)”
  3. unzip it, copy and paste “six.py” into your source directory.
  4. import “six” module into your source code (import six)
  5. run source script.

回答 5

pip install --ignore-installed six

资料来源:1233个竖起大拇指在此评论

pip install --ignore-installed six

Source: 1233 thumbs up on this comment


回答 6

在Ubuntu Bionic(18.04)上,已经为python2和python3安装了六个,但是启动Wammu时出现错误。@ 3ygun解决方案为我解决了

ImportError: No module named six

启动Wammu时

如果发生在python3程序中,则附带六个

pip3 install six

如果没有pip3:

apt install python3-pip

在Ubuntu下使用sudo

on Ubuntu Bionic (18.04), six is already install for python2 and python3 but I have the error launching Wammu. @3ygun solution worked for me to solve

ImportError: No module named six

when launching Wammu

If it’s occurred for python3 program, six come with

pip3 install six

and if you don’t have pip3:

apt install python3-pip

with sudo under Ubuntu!


ImportError:Windows上没有模块命名的站点

问题:ImportError:Windows上没有模块命名的站点

我正在尝试首次安装Python。我从Python网站下载了以下安装程序: Python 2.7.1 Windows Installer(Windows二进制文件-不包括源代码)。然后,我运行安装程序,选择“所有用户”,一切都很好。我将Python安装到默认位置:

C:\Python27

接下来,要测试Python是否已正确安装,我导航到我的Python目录,并在Windows cmd提示符下运行了“ python”命令。它返回以下错误:

ImportError:没有名为站点的模块

当我执行“ python -v”时,我得到以下信息:

#installing zipimport hook
import zipimport # builtin

#ImportError: No module named site #installed zipimport钩子#clear 内置 ._
#clear sys.path #clear sys.argv
#clear sys.ps1 #clear sys.ps2
#clear sys.exitfunc #clear sys.exc_type
#clear sys.exc_value #clear sys.exc_traceback
#clear sys.last_type #clear sys.last_value
#clear sys.last_traceback #clear sys.path_hooks
#clear sys.path_importer_cache #clear sys.meta_path
#clear sys.flags #clear sys.float_info
#restore sys.stdin #恢复sys.stdout
#restore sys.stderr #cleanup
#cleanup [1 ] zipimport #cleanup [1]信号
#cleanup[1 ] exceptions #cleanup [1] _warnings
#cleanup sys 内置的
#cleanup ints: 6 unfreed ints cleanup #cleanup浮动

当我执行dir时,C:\Python27\Lib\site.py*我得到以下信息:

C:\ Users \ Mimminito> dir C:\ Python27 \ Lib \ site.py *
驱动器C中的卷没有标签。
卷序列号是DAB9-A863

C:\ Python27 \ Lib目录

13/11/2010 20:08 20,389 site.py
1文件20,389字节
0目录694,910,976字节免费

有任何想法吗?

I am trying to install Python for the first time. I downloaded the following installer from the Python website: Python 2.7.1 Windows Installer (Windows binary — does not include source). I then ran the installer, selected ‘All Users’ and all was fine. I installed Python into the default location:

C:\Python27

Next, to test that Python was installed correctly, I navigated to my Python Directory, and ran the “python” command in the windows cmd prompt. It returns me the following error:

ImportError: No module named site

When I do ‘python -v’ I get the following:

#installing zipimport hook
import zipimport # builtin
#installed zipimport hook
#ImportError: No module named site #clear builtin._
#clear sys.path #clear sys.argv
#clear sys.ps1 #clear sys.ps2
#clear sys.exitfunc #clear sys.exc_type
#clear sys.exc_value #clear sys.exc_traceback
#clear sys.last_type #clear sys.last_value
#clear sys.last_traceback #clear sys.path_hooks
#clear sys.path_importer_cache #clear sys.meta_path
#clear sys.flags #clear sys.float_info
#restore sys.stdin #restore sys.stdout
#restore sys.stderr #cleanup main
#cleanup[1] zipimport #cleanup[1] signal
#cleanup[1] exceptions #cleanup[1] _warnings
#cleanup sys #cleanup builtin
#cleanup ints: 6 unfreed ints #cleanup floats

When I do dir C:\Python27\Lib\site.py* I get the following:

C:\Users\Mimminito>dir C:\Python27\Lib\site.py*
Volume in drive C has no label.
Volume Serial Number is DAB9-A863

Directory of C:\Python27\Lib

13/11/2010 20:08 20,389 site.py
1 File(s) 20,389 bytes
0 Dir(s) 694,910,976 bytes free

Any ideas?


回答 0

我已经为自己研究了近一天的问题,终于取得了突破。试试这个:

  1. 设置PYTHONPATH / PYTHONHOME变量

    右键单击开始菜单中的“ 计算机”图标,然后转到属性。在左侧标签上,转到高级系统设置。在出现的窗口中,转到“ 高级”选项卡,然后在底部单击“ 环境变量”。单击用户变量列表,然后开始键入Python,然后重复“ 系统变量”,以确保您没有为PYTHONPATH或PYTHONHOME设置错误的变量。接下来,添加新变量(我也可以在System中而不是User中使用,尽管它也可能对User也适用):PYTHONPATH,设置为C:\ Python27 \ Lib。,设置为C:\ Python27PYTHONHOME

希望这可以帮助!

I’ve been looking into this problem for myself for almost a day and finally had a breakthrough. Try this:

  1. Setting the PYTHONPATH / PYTHONHOME variables

    Right click the Computer icon in the start menu, go to properties. On the left tab, go to Advanced system settings. In the window that comes up, go to the Advanced tab, then at the bottom click Environment Variables. Click in the list of user variables and start typing Python, and repeat for System variables, just to make certain that you don’t have mis-set variables for PYTHONPATH or PYTHONHOME. Next, add new variables (I did in System rather than User, although it may work for User too): PYTHONPATH, set to C:\Python27\Lib. PYTHONHOME, set to C:\Python27.

Hope this helps!


回答 1

快速解决方案:设置PYTHONHOME和PYTHONPATH并在PATH上包含PYTHONHOME

例如,如果您安装到c:\ Python27

set PYTHONHOME=c:\Python27
set PYTHONPATH=c:\Python27\Lib
set PATH=%PYTHONHOME%;%PATH%

确保您在PYTHON *变量上没有结尾的’\’,这似乎会使它破坏。

Quick solution: set PYTHONHOME and PYTHONPATH and include PYTHONHOME on PATH

For example if you installed to c:\Python27

set PYTHONHOME=c:\Python27
set PYTHONPATH=c:\Python27\Lib
set PATH=%PYTHONHOME%;%PATH%

Make sure you don’t have a trailing ‘\’ on the PYTHON* vars, this seems to break it aswel.


回答 2

在安装Windows Python和Cygwin Python并尝试从Cygwin运行Cygwin Python之后,出现了这个问题。我export通过PYTHONHOME = / usr /和PYTHONPATH = / usr / lib / python2.7 解决了它

I was having this issue after installing both Windows Python and Cygwin Python, and trying to run Cygwin Python from Cygwin. I solved it by exporting PYTHONHOME=/usr/ and PYTHONPATH=/usr/lib/python2.7


回答 3

确保正确设置了PYTHONHOME环境变量。如果PYTHONHOME指向无效的位置或您要运行的其他Python安装,您将收到此错误。

试试这个:

C:\>set PYTHONHOME=C:\Python27
C:\>python

setx PYTHONHOME C:\Python27

将其永久设置为后续命令提示符

Make sure your PYTHONHOME environment variable is set correctly. You will receive this error if PYTHONHOME is pointing to invalid location or to another Python installation you are trying to run.

Try this:

C:\>set PYTHONHOME=C:\Python27
C:\>python

Use

setx PYTHONHOME C:\Python27

to set this permanently for subsequent command prompts


回答 4

找到site.py并将其路径添加到PYTHONPATH中。这样可以解决您的问题。

Locate site.py and add its path in PYTHONPATH. This will solve your problem.


回答 5

您是否要从Cygwin运行Windows Python?我有同样的问题。Cygwin中的Python无法导入站点。Cmd中的Python可以工作。

看起来您需要确保通过以下方式运行PYTHONHOME和PYTHONPATH cygwin -aw来使它们成为Windows路径。另外,python似乎使用了一些不正确的路径。

我想我需要通过cygwin安装python才能正常工作。

Are you trying to run Windows Python from Cygwin? I’m having the same problem. Python in Cygwin fails to import site. Python in Cmd works.

It looks like you need to make sure you run PYTHONHOME and PYTHONPATH through cygwin -aw to make them Windows paths. Also, python seems to be using some incorrect paths.

I think I’ll need to install python through cygwin to get it working.


回答 6

对于Windows 10(按照@slckin回答),可以通过以下命令在命令行中进行设置:

setx PYTHONHOME "C:\Python27"
setx PYTHONPATH "C:\Python27\Lib"
setx PATH "%PYTHONHOME%;%PATH%"

For Windows 10 (follow up on @slckin answer), this can be set through the command line with:

setx PYTHONHOME "C:\Python27"
setx PYTHONPATH "C:\Python27\Lib"
setx PATH "%PYTHONHOME%;%PATH%"

回答 7

就我而言,问题是另一个site.py文件,由于PATH设置,它比Python \ Lib中的文件更早被解决。

环境:Windows 10 Pro,Python27。

我的桌面安装了pgAdmin,它具有文件C:\ Program Files(x86)\ pgAdmin \ venv \ Lib \ site.py。由于PATH环境变量比Python更早拥有pdAdmin的目录(显然这是一个坏主意),因此首先找到pgAdmin的site.py。

解决该问题所需要做的就是在PATH中将pgAdmin的主页移到比Python晚的地方

In my case, the issue was another site.py file, that was resolved earlier than the one from Python\Lib, due to PATH setting.

Environment: Windows 10 Pro, Python27.

My desktop has pgAdmin installed, which has file C:\Program Files (x86)\pgAdmin\venv\Lib\site.py. Because PATH environment variable had pdAdmin’s home earlier than Python (apparently a bad idea in the first place), pgAdmin’s site.py was found first.

All I had to do to fix the issue was to move pgAdmin’s home later than Python, in PATH


回答 8

对我而言,发生这种情况是因为我安装了2个版本的python-python 27和python 3.3。这两个文件夹都设置了路径变量,因此存在此问题。为了解决这个问题,我将python27移到了temp文件夹,因为我对python 3.3没问题。因此,请检查诸如PATH,PYTHONHOME之类的环境变量,因为这可能是一个问题。谢谢。

For me it happened because I had 2 versions of python installed – python 27 and python 3.3. Both these folder had path variable set, and hence there was this issue. To fix, this, I moved python27 to temp folder, as I was ok with python 3.3. So do check environment variables like PATH,PYTHONHOME as it may be a issue. Thanks.


回答 9

如果有人发现非管理员用户仍无法使用它:

错误示例:

ImportError: No module named iso8601

您需要为easy_install设置“ –always-unzip”选项:

easy_install --always-unzip python-keystoneclient

它将解压缩您的egg文件,并允许导入找到em。

If somebody will find that it’s still not working under non-admin users:

Example error:

ImportError: No module named iso8601

you need to set ‘–always-unzip’ option for easy_install:

easy_install --always-unzip python-keystoneclient

It will unzip your egg files and will allow import to find em.


回答 10

ImportError: No module named site在安装python 2.7.11时遇到了同样的问题

最初我有Python2.5,PYTHONHOME路径设置为Python2.5。我将其重命名为,C:\Python27\并解决了该问题。

I went through the same issue of ImportError: No module named site while installing python 2.7.11

Initially I had Python2.5 and the PYTHONHOME path was set to Python2.5. I renamed it to C:\Python27\ and it resolved the problem.


回答 11

您可以尝试“ 开源Active Python设置”,它是Windows的出色Python安装程序。您只需要卸载并安装版本即可。

You may try the Open Source Active Python Setup which is a well done Python installer for Windows. You just have to desinstall your version and install it…


回答 12

我对slckin的答案投了赞成票。我的问题是我考虑周全,并在路径周围加了双引号。我删除了所有三个变量的双引号:PYTHONHOME,PYTHONPATH和PATH。请注意,该文件位于cmd或bat文件中,用于设置其他工具的环境。但是,双引号可能在图标设置中很有用。打字

揭示了报价在路径中的位置而不是按预期下降。我还缩短了PATH,使其长度少于256个字符。

I up voted slckin’s answer. My problem was that I was thoughtful and added double quotes around the paths. I removed the double quotes in all of the three variables: PYTHONHOME, PYTHONPATH, and PATH. Note that this was in a cmd or bat file to setup the environment for other tools. However, the double quotes may be useful in an icon setting. Typing

set

revealed that the quotes where in the path and not dropped as expected. I also shorted the PATH so that it was less than 256 characters long.


回答 13

我有一个非常依赖Python的应用程序,并随着新版本的发布保持python 2.7.x的最新性。直到2.7.11,当我遇到相同的No module named site错误时,一切都很好。我已将PYTHONHOME设置为c:\Python27且正在运行。但是仍然有一个谜,为什么在以前的版本中不需要它,现在需要这样做。而且,如果需要,安装程序为什么不设置此变量?

I have an application which relies heavily on Python and have kept up-to-date with python 2.7.x as new versions are released. Everthing has been fine until 2.7.11 when I got the same “No module named site” error. I’ve set PYTHONHOME to c:\Python27 and it’s working. But the mystery remains why this is now needed when it wasn’t with previous releases. And, if it is needed, why doesn’t the installer set this var?


回答 14

我有同样的问题。我的解决方案是修复Python安装。(这是一个新安装,因此我没想到会出现问题,但现在已解决。)

要修复(Windows 7):

  1. 转到控制面板->程序->程序和功能
  2. 单击已安装的Python版本,然后按“卸载/更改”。
  3. 请按照说明修复安装。

I had the same problem. My solution was to repair the Python installation. (It was a new installation so I did not expect a problem but now it is solved.)

To repair (Windows 7):

  1. go to Control Panel -> Programs -> Programs and Features
  2. click on the Python version installed and then press Uninstall/Change.
  3. follow the instructions to repair the installation.

回答 15

从PyYAML主页安装yaml:http ://www.pyyaml.org/wiki/PyYAML

选择适合您的OS和Python的版本。

Install yaml from the PyYAML home pagee: http://www.pyyaml.org/wiki/PyYAML

Select the appropriate version for your OS and Python.


有没有一种标准的方法可以在软件包中列出Python模块的名称?

问题:有没有一种标准的方法可以在软件包中列出Python模块的名称?

有没有一种简单的方法可以列出软件包中所有模块的名称,而无需使用__all__

例如,给定此程序包:

/testpkg
/testpkg/__init__.py
/testpkg/modulea.py
/testpkg/moduleb.py

我想知道是否有标准或内置的方式来做这样的事情:

>>> package_contents("testpkg")
['modulea', 'moduleb']

手动方法是遍历模块搜索路径,以找到包的目录。然后可以列出该目录中的所有文件,过滤出唯一命名为py / pyc / pyo的文件,剥离扩展名,然后返回该列表。但这对于模块导入机制已经在内部完成的工作来说似乎是相当多的工作。该功能在任何地方都可以使用吗?

Is there a straightforward way to list the names of all modules in a package, without using __all__?

For example, given this package:

/testpkg
/testpkg/__init__.py
/testpkg/modulea.py
/testpkg/moduleb.py

I’m wondering if there is a standard or built-in way to do something like this:

>>> package_contents("testpkg")
['modulea', 'moduleb']

The manual approach would be to iterate through the module search paths in order to find the package’s directory. One could then list all the files in that directory, filter out the uniquely-named py/pyc/pyo files, strip the extensions, and return that list. But this seems like a fair amount of work for something the module import mechanism is already doing internally. Is that functionality exposed anywhere?


回答 0

也许这会满足您的需求?

import imp
import os
MODULE_EXTENSIONS = ('.py', '.pyc', '.pyo')

def package_contents(package_name):
    file, pathname, description = imp.find_module(package_name)
    if file:
        raise ImportError('Not a package: %r', package_name)
    # Use a set because some may be both source and compiled.
    return set([os.path.splitext(module)[0]
        for module in os.listdir(pathname)
        if module.endswith(MODULE_EXTENSIONS)])

Maybe this will do what you’re looking for?

import imp
import os
MODULE_EXTENSIONS = ('.py', '.pyc', '.pyo')

def package_contents(package_name):
    file, pathname, description = imp.find_module(package_name)
    if file:
        raise ImportError('Not a package: %r', package_name)
    # Use a set because some may be both source and compiled.
    return set([os.path.splitext(module)[0]
        for module in os.listdir(pathname)
        if module.endswith(MODULE_EXTENSIONS)])

回答 1

使用python2.3及更高版本,您还可以使用以下pkgutil模块:

>>> import pkgutil
>>> [name for _, name, _ in pkgutil.iter_modules(['testpkg'])]
['modulea', 'moduleb']

编辑:请注意,该参数不是模块列表,而是路径列表,因此您可能需要执行以下操作:

>>> import os.path, pkgutil
>>> import testpkg
>>> pkgpath = os.path.dirname(testpkg.__file__)
>>> print [name for _, name, _ in pkgutil.iter_modules([pkgpath])]

Using python2.3 and above, you could also use the pkgutil module:

>>> import pkgutil
>>> [name for _, name, _ in pkgutil.iter_modules(['testpkg'])]
['modulea', 'moduleb']

EDIT: Note that the parameter is not a list of modules, but a list of paths, so you might want to do something like this:

>>> import os.path, pkgutil
>>> import testpkg
>>> pkgpath = os.path.dirname(testpkg.__file__)
>>> print [name for _, name, _ in pkgutil.iter_modules([pkgpath])]

回答 2

import module
help(module)
import module
help(module)

回答 3

不知道我是在忽略什么,还是答案只是过时而已;

如user815423426所述,这仅适用于活动对象,并且列出的模块仅是之前导入的模块。

使用inspect列出软件包中的模块似乎真的很容易:

>>> import inspect, testpkg
>>> inspect.getmembers(testpkg, inspect.ismodule)
['modulea', 'moduleb']

Don’t know if I’m overlooking something, or if the answers are just out-dated but;

As stated by user815423426 this only works for live objects and the listed modules are only modules that were imported before.

Listing modules in a package seems really easy using inspect:

>>> import inspect, testpkg
>>> inspect.getmembers(testpkg, inspect.ismodule)
['modulea', 'moduleb']

回答 4

这是适用于python 3.6及更高版本的递归版本:

import importlib.util
from pathlib import Path
import os
MODULE_EXTENSIONS = '.py'

def package_contents(package_name):
    spec = importlib.util.find_spec(package_name)
    if spec is None:
        return set()

    pathname = Path(spec.origin).parent
    ret = set()
    with os.scandir(pathname) as entries:
        for entry in entries:
            if entry.name.startswith('__'):
                continue
            current = '.'.join((package_name, entry.name.partition('.')[0]))
            if entry.is_file():
                if entry.name.endswith(MODULE_EXTENSIONS):
                    ret.add(current)
            elif entry.is_dir():
                ret.add(current)
                ret |= package_contents(current)


    return ret

This is a recursive version that works with python 3.6 and above:

import importlib.util
from pathlib import Path
import os
MODULE_EXTENSIONS = '.py'

def package_contents(package_name):
    spec = importlib.util.find_spec(package_name)
    if spec is None:
        return set()

    pathname = Path(spec.origin).parent
    ret = set()
    with os.scandir(pathname) as entries:
        for entry in entries:
            if entry.name.startswith('__'):
                continue
            current = '.'.join((package_name, entry.name.partition('.')[0]))
            if entry.is_file():
                if entry.name.endswith(MODULE_EXTENSIONS):
                    ret.add(current)
            elif entry.is_dir():
                ret.add(current)
                ret |= package_contents(current)


    return ret

回答 5

根据cdleary的示例,这是所有子模块的递归版本列表路径:

import imp, os

def iter_submodules(package):
    file, pathname, description = imp.find_module(package)
    for dirpath, _, filenames in os.walk(pathname):
        for  filename in filenames:
            if os.path.splitext(filename)[1] == ".py":
                yield os.path.join(dirpath, filename)

Based on cdleary’s example, here’s a recursive version listing path for all submodules:

import imp, os

def iter_submodules(package):
    file, pathname, description = imp.find_module(package)
    for dirpath, _, filenames in os.walk(pathname):
        for  filename in filenames:
            if os.path.splitext(filename)[1] == ".py":
                yield os.path.join(dirpath, filename)

回答 6

这应该列出模块:

help("modules")

This should list the modules:

help("modules")

回答 7

如果您想在python代码之外查看有关软件包的信息(从命令提示符),则可以使用pydoc。

# get a full list of packages that you have installed on you machine
$ python -m pydoc modules

# get information about a specific package
$ python -m pydoc <your package>

您将获得与pydoc相同的结果,但在解释器中使用help

>>> import <my package>
>>> help(<my package>)

If you would like to view an inforamtion about your package outside of the python code (from a command prompt) you can use pydoc for it.

# get a full list of packages that you have installed on you machine
$ python -m pydoc modules

# get information about a specific package
$ python -m pydoc <your package>

You will have the same result as pydoc but inside of interpreter using help

>>> import <my package>
>>> help(<my package>)

回答 8

def package_contents(package_name):
  package = __import__(package_name)
  return [module_name for module_name in dir(package) if not module_name.startswith("__")]
def package_contents(package_name):
  package = __import__(package_name)
  return [module_name for module_name in dir(package) if not module_name.startswith("__")]

回答 9

打印目录(模块)

print dir(module)


在python模块docstring中放什么?[关闭]

问题:在python模块docstring中放什么?[关闭]

好的,我已经阅读了PEP 8PEP 257,并且为函数和类编写了许多文档字符串,但是我不确定模块文档字符串中应该包含什么。我认为,至少它应该记录该模块导出的功能和类,但是我也看到了一些列出作者姓名,版权信息等的模块。有没有人举过一个很好的python docstring应该怎么做的例子。有条理?

Ok, so I’ve read both PEP 8 and PEP 257, and I’ve written lots of docstrings for functions and classes, but I’m a little unsure about what should go in a module docstring. I figured, at a minimum, it should document the functions and classes that the module exports, but I’ve also seen a few modules that list author names, copyright information, etc. Does anyone have an example of how a good python docstring should be structured?


回答 0

考虑一个help(yourmodule)在交互式口译员提示下做的人-他们知道什么?(其他提取和显示信息的方法在信息量方面大致相同help)。因此,如果您有x.py

"""This module does blah blah."""

class Blah(object):
  """This class does blah blah."""

然后:

>>> import x; help(x)

显示:

Help on module x:

NAME
    x - This module does blah blah.

FILE
    /tmp/x.py

CLASSES
    __builtin__.object
        Blah

    class Blah(__builtin__.object)
     |  This class does blah blah.
     |  
     |  Data and other attributes defined here:
     |  
     |  __dict__ = <dictproxy object>
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__ = <attribute '__weakref__' of 'Blah' objects>
     |      list of weak references to the object (if defined)

如您所见,这些组件的文档字符串中已经包含了有关类的详细信息(以及函数,尽管这里没有显示)。该模块自己的文档字符串应该非常简要地描述它们(如果有的话),而应该专注于该模块作为一个整体可以为您做什么的简要概述,理想情况下是带有一些经过文档测试的示例(就像函数和类在理想情况下应该在文档中经过文档测试的示例一样)他们的文档字符串)。

我看不到诸如作者姓名和版权/许可证之类的元数据如何帮助该模块的用户-而是可以添加注释,因为它可以帮助某些人考虑是否重用或修改该模块。

Think about somebody doing help(yourmodule) at the interactive interpreter’s prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help in terms of amount of information). So if you have in x.py:

"""This module does blah blah."""

class Blah(object):
  """This class does blah blah."""

then:

>>> import x; help(x)

shows:

Help on module x:

NAME
    x - This module does blah blah.

FILE
    /tmp/x.py

CLASSES
    __builtin__.object
        Blah

    class Blah(__builtin__.object)
     |  This class does blah blah.
     |  
     |  Data and other attributes defined here:
     |  
     |  __dict__ = <dictproxy object>
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__ = <attribute '__weakref__' of 'Blah' objects>
     |      list of weak references to the object (if defined)

As you see, the detailed information on the classes (and functions too, though I’m not showing one here) is already included from those components’ docstrings; the module’s own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).

I don’t see how metadata such as author name and copyright / license helps the module’s user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.


回答 1

引用规格

脚本 (独立程序)的文档字符串应可用作其“使用情况”消息,在使用不正确或缺失的参数(或者可能使用“ -h”选项表示“帮助”)调用脚本时打印。这样的文档字符串应记录脚本的功能和命令行语法,环境变量和文件。使用情况消息可能非常详尽(几个屏幕已满),并且对于新用户而言,足以正确使用该命令,并且对于高级用户而言,它是对所有选项和参数的完整快速参考。

模块的文档字符串 通常应列出该模块导出的类,异常和函数(以及任何其他对象),并以每行的一行摘要显示。(这些摘要所提供的详细信息通常少于对象的文档字符串中的摘要行。)程序包的文档字符串(即,程序包__init__.py模块的文档字符串)也应列出由程序包导出的模块和子程序包。

的文档字符串 应总结其行为,并列出公共方法和实例变量。如果该类打算被子类化,并且具有子类的附加接口,则该接口应单独列出(在文档字符串中)。类构造函数的方法应记录在文档字符串中__init__。各个方法应由自己的文档字符串记录。

函数方法的文档字符串 是一个以句点结尾的短语。它将函数或方法的效果规定为命令(“执行此操作”,“返回该值”),而不是说明。例如,不要写“返回路径名…”。函数或方法的多行文档字符串应总结其行为并记录其自变量,返回值,副作用,引发的异常以及何时可以调用它的限制(所有这些均适用)。应该指出可选参数。应该记录关键字参数是否是接口的一部分。

To quote the specifications:

The docstring of a script (a stand-alone program) should be usable as its “usage” message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a “-h” option, for “help”). Such a docstring should document the script’s function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.

The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object’s docstring.) The docstring for a package (i.e., the docstring of the package’s __init__.py module) should also list the modules and subpackages exported by the package.

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.

The docstring of a function or method is a phrase ending in a period. It prescribes the function or method’s effect as a command (“Do this”, “Return that”), not as a description; e.g. don’t write “Returns the pathname …”. A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.


PyCharm错误:尝试导入自己的模块时(“ Python模块”)为“无模块”

问题:PyCharm错误:尝试导入自己的模块时(“ Python模块”)为“无模块”

我已经编写了一个模块(位于文件my_mod.py夹中的文件文件my_module)。目前,我正在处理文件cool_script.py夹中的文件cur_proj。我已经使用File-open在PyCharm中打开了该文件夹(我假设是一个PyCharm项目)。

在ProjectView(CMD-7)中,我可以看到我的项目cur_proj(红色),并且在“外部库”下可以看到my_module。在cool_script.py中,我可以写

from my_module import my_mod as mm

PyCharm甚至建议my_mod。到目前为止,一切都很好。

但是,当我尝试运行cool_script.py时,PyCharm告诉我 “没有名为my_module的模块”

我觉得这很奇怪,因为

A)在终端(OS 10.10.2)中,在python中,我可以导入模块没有问题-.bashrc中的PYTHONPATH中有相应的条目

B)在PyCharm中-设置-项目cur_proj-项目解释器-python解释器旁边的CogWheel-更多-显示所选解释器图标的路径,PYTHONPATH的路径确实出现(我认为应该如此)

因此,为什么在尝试运行cool_script.py时出现错误?- 我想念什么?

笔记:

附录2015年2月25日

当我进入PyCharm以运行-编辑配置时,对于当前项目,有两个选中的选项带有复选标记:“ 将内容根添加到PYTHONPATH ”和“ 将源根添加到PYTHONPATH ”。当我都取消选中时,我可以加载我的模块。

现在就可以了- 但是为什么呢?

出现了其他问题:

  • 什么是“内容根”和什么是“源根”?为什么在PYTHONPATH中添加一些内容却使其以某种方式中断?
  • 我是否应该一直取消选中这两个选项(在默认设置中也要取消选中这两个选项,而不是仅针对项目特定的配置(“运行/调试配置”对话框的左侧面板)?

I have written a module (a file my_mod.py file residing in the folder my_module). Currently, I am working in the file cool_script.py that resides in the folder cur_proj. I have opened the folder in PyCharm using File — open (and I assume, hence, it is a PyCharm project).

In ProjectView (CMD-7), I can see my project cur_proj (in red) and under “External Libraries” I do see my_module. In cool_script.py, I can write

from my_module import my_mod as mm

and PyCharm even makes suggestion for my_mod. So far so good.

However, when I try to run cool_script.py, PyCharm tells me “No module named my_module”

This seems strange to me, because

A) in the terminal (OS 10.10.2), in python, I can import the module no problem — there is a corresponding entry in the PYTHONPATH in .bashrc

B) in PyCharm — Settings — Project cur_proj — Project Interpreter — CogWheel next to python interpreter — more — show paths for selected interpreter icon, the paths from PYTHONPATH do appear (as I think they should)

Hence, why do I get the error when I try to run cool_script.py? — What am I missing?

Notes:

Addendum 2015-Feb-25

When I go in PyCharm to Run — Edit Configurations, for my current project, there are two options that are selected with a check mark: “Add content roots to PYTHONPATH” and “Add source roots to PYTHONPATH“. When I have both unchecked, I can load my module.

So it works now — but why?

Further questions emerged:

  • What are “content roots” and what are “source roots”? And why does adding something to the PYTHONPATH make it somehow break?
  • should I uncheck both of those options all the time (so also in the defaults, not only the project specific configurations (left panel of the Run/Debug Configurations dialog)?

回答 0

如果您自己的模块在同一路径中,则需要将该路径标记为Sources Root。在项目浏览器中,右键单击要导入的目录。然后选择Mark Directory As,然后选择Sources Root

我希望这有帮助。

If your own module is in the same path, you need mark the path as Sources Root. In the project explorer, right-click on the directory that you want import. Then select Mark Directory As and select Sources Root.

I hope this helps.


回答 1

所以如果你去

->设置->项目:My_project->项目结构,

仅提供源代码所在的目录,并将其标记为“源”(您可以在同一窗口中看到它)。带有源代码的目录应变为蓝色。现在,您可以导入位于同一目录中的模块。

So if you go to

-> Setting -> Project:My_project -> Project Structure,

Just the directory in which the source code is available and mark it as “Sources” (You can see it on the same window). The directory with source code should turn blue. Now u can import in modules residing in same directory.


回答 2

PyCharm社区/专业版2018.2.1

我现在遇到了这个问题,并且能够以类似于@Beatriz Fonseca和@Julie指出的方式解决它。

如果转到File-> Settings-> Project: YourProjectName-> Project Structure,则将具有当前正在处理的项目的目录布局。必须浏览目录并将其标记Source为所有源文件的目录,或作为Resource严格导入文件的文件夹。

您还需要确保将__init__.py文件放置在资源目录中,或者实际上是要导入的任何位置,并且可以很好地工作。

我希望这个答案对某人有帮助,并希望JetBrains可以解决此烦人的错误。

PyCharm Community/Professional 2018.2.1

I was having this problem just now and I was able to solve it in sort of a similar way that @Beatriz Fonseca and @Julie pointed out.

If you go to File -> Settings -> Project: YourProjectName -> Project Structure, you’ll have a directory layout of the project you’re currently working in. You’ll have to go through your directories and label them as being either the Source directory for all your Source files, or as a Resource folder for files that are strictly for importing.

You’ll also want to make sure that you place __init__.py files within your resource directories, or really anywhere that you want to import from, and it’ll work perfectly fine.

I hope this answer helps someone, and hopefully JetBrains will fix this annoying bug.


回答 3

我尝试的是获取文件所在的位置。

例如 E:\git_projects\My_project\__init__.py is my location.

我转到文件->设置->项目:My_project->项目结构,然后将内容根添加到要提到的地方 E:\git_projects\My_project

它为我工作。

What I tried is to source the location where my files are.

e.g. E:\git_projects\My_project\__init__.py is my location.

I went to File -> Setting -> Project:My_project -> Project Structure and added the content root to about mention place E:\git_projects\My_project

it worked for me.


回答 4

my_module是不是模块的文件夹,您不能导入文件夹,请尝试移至my_mod.py与相同的文件夹cool_script.py,然后执行import my_mod as mm。这是因为python仅在当前目录和中sys.path查找,因此my_mod.py除非在同一目录中,否则不会找到

或者,您可以在此处找到答案,告诉您如何从其他目录导入。

关于您的其他问题,我不知道我不使用PyCharm。

my_module is a folder not a module and you can’t import a folder, try moving my_mod.py to the same folder as the cool_script.py and then doimport my_mod as mm. This is because python only looks in the current directory and sys.path, and so wont find my_mod.py unless it’s in the same directory

Or you can look here for an answer telling you how to import from other directories.

As to your other questions, I do not know as I do not use PyCharm.


回答 5

我也收到“将源根添加到PYTHONPATH”错误。我的问题是我有两个具有相同名称的文件夹,例如project/subproject1/thing/src和,project/subproject2/thing/src并且两个文件夹都标记为源根。当我将其中一个"thing"文件夹重命名为"thing1"(任何唯一的名称)时,它起作用了。

也许PyCharm自动添加选定的源根目录,它不会使用完整路径,因此会混淆具有相同名称的文件夹。

I was getting the error with “Add source roots to PYTHONPATH” as well. My problem was that I had two folders with the same name, like project/subproject1/thing/src and project/subproject2/thing/src and I had both of them marked as source root. When I renamed one of the "thing" folders to "thing1" (any unique name), it worked.

Maybe if PyCharm automatically adds selected source roots, it doesn’t use the full path and hence mixes up folders with the same name.


回答 6

当Python解释器找不到您的代码时,可能会导致这种情况。您必须向Python明确提及才能在此位置找到您的代码。

为此:

  • 转到您的python控制台
  • 添加sys.path.extend(['your module location'])到Python控制台。

在您的情况下:

  • 转到您的python控制台,
  • 首先,编写以下代码:

    import sys
    sys.path.extend([my module URI location])
  • 编写此语句后,可以运行以下命令:

    from mymodule import functions

This can be caused when Python interpreter can’t find your code. You have to mention explicitly to Python to find your code in this location.

To do so:

  • Go to your python console
  • Add sys.path.extend(['your module location']) to Python console.

In your case:

  • Go to your python console,
  • On the start, write the following code:

    import sys
    sys.path.extend([my module URI location])
    
  • Once you have written this statement you can run following command:

    from mymodule import functions
    

回答 7

必须完成的关键混乱步骤是为您要执行的源文件重新创建运行配置,以便IDE选择新路径。

对我而言,真正有效的方法是转到“运行/编辑配置…”,为您要在左侧运行的文件选择配置,取消选中“将源根添加到PYTHONPATH”框,保存,然后返回并选中该框并保存。然后它会工作。

The key confusing step that must be done is to recreate the run configuration for the source file that you’re trying to execute, so that the IDE picks up the new paths.

The way that actually worked for me was to go to Run/Edit Configurations…, select the configuration for the file that you’re trying to run on the left side, uncheck the “Add source roots to PYTHONPATH” box, save, and then go back and check the box and save. THEN it would work.


回答 8

内容根是保存项目代码的文件夹,而源根也被定义为相同的文件夹。我唯一了解的区别是,源根目录中的代码是在内容根目录中的代码之前构建的。

取消选中它们不会影响运行时,直到您没有在程序包中创建单独的模块(这些模块已手动连接到Django)为止。这意味着,如果您的任何文件不包含“ from django import …”或未通过django调用任何功能,则取消选中这两个选项将导致故障。

更新-仅在使用Virtual Environmanet时出现问题,并且仅在通过提供的终端控制项目时出现。因为终端仍然可以通过默认系统pyhtonpath而不是虚拟环境工作。而python django控制面板可以正常工作。

Content roots are folders holding your project code while source roots are defined as same too. The only difference i came to understand was that the code in source roots is built before the code in the content root.

Unchecking them wouldn’t affect the runtime till the point you’re not making separate modules in your package which are manually connected to Django. That means if any of your files do not hold the ‘from django import…’ or any of the function isn’t called via django, unchecking these 2 options will result in a malfunction.

Update – the problem only arises when using Virtual Environmanet, and only when controlling the project via the provided terminal. Cause the terminal still works via the default system pyhtonpath and not the virtual env. while the python django control panel works fine.


回答 9

解决此问题而不必将目录标记为源根的解决方案是编辑运行配置,然后在执行中选择选项“重定向输入自”,然后选择要运行的脚本。之所以可行,是因为随后将其视为脚本是在此目录中以交互方式运行。但是,Python仍会使用错误“没有名为x的模块”来标记模块名称:

解释器执行import语句时,它将在从以下来源汇编的目录列表中搜索x.py:

  1. 运行输入脚本的目录或当前目录(如果解释器正在交互运行)
  2. PYTHONPATH环境变量(如果已设置)中包含的目录列表。
  3. 在安装Python时配置的与安装有关的目录列表,在我的情况下为Ubuntu上的usr / lib / python3.6。

The solution for this problem without having to Mark Directory as Source Root is to Edit Run Configurations and in Execution select the option “Redirect input from” and choose script you want to run. This works because it is then treated as if the script was run interactively in this directory. However Python will still mark the module name with an error “no module named x”:

When the interpreter executes the import statement, it searches for x.py in a list of directories assembled from the following sources:

  1. The directory from which the input script was run or the current directory if the interpreter is being run interactively
  2. The list of directories contained in the PYTHONPATH environment variable, if it is set.
  3. An installation-dependent list of directories configured at the time Python is installed, in my case usr/lib/python3.6 on Ubuntu.

回答 10

Pycharm 2017.1.1

  1. 点击View->ToolBarView->Tool Buttons
  2. 在左窗格Project上将可见,右键单击它,然后按Autoscroll to source ,然后运行您的代码。

这对我有用。

Pycharm 2017.1.1

  1. Click on View->ToolBar & View->Tool Buttons
  2. On the left pane Project would be visible, right click on it and press Autoscroll to source and then run your code.

This worked for me.


回答 11

ln -s someProject

如果您有someDirectory / someProjectDir和两个文件,则file1.py和file2.py,以及file1.py尝试使用此行导入

从someProjectDir导入file2

即使您已将someProjectDir指定为源目录,并且即使它在首选项中也将项目,项目结构菜单显示为内容根目录,它也无法使用。它将起作用的唯一方法是通过链接如上所示的项目(unix命令,在Mac中工作,不确定Windows的使用或语法)。由于软链接是由Pycharm在依赖项目中创建的,因此似乎存在某种机制,Pycharm可以在从版本控制签出或作为上下文根添加时自动执行此操作。因此,尽管复制了相同的内容,但奇怪的是目录的复制令人烦恼,而必要性却令人困惑。同样在自动创建的依赖项中,它在版本控制下也不显示为新目录。.idea文件的比较可能会发现更多。

ln -s . someProject

If you have someDirectory/someProjectDir and two files, file1.py and file2.py, and file1.py tries to import with this line

from someProjectDir import file2

It won’t work, even if you have designated the someProjectDir as a source directory, and even if it shows in preferences, project, project structure menu as a content root. The only way it will work is by linking the project as show above (unix command, works in mac, not sure of use or syntax for Windows). There seems some mechanism where Pycharm does this automatically either in checkout from version control or adding as context root, since the soft link was created by Pycharm in a dependent project. Hence, just copying the same, although the weird replication of directory is annoying and necessity is perplexing. Also in the dependency where auto created, it doesn’t show as new directory under version control. Perhaps comparison of .idea files will reveal more.


回答 12

对我有用的答案确实是OP在他的2015年更新中提到的内容:取消选中Python运行配置中的以下两个框

  • “将内容根添加到PYTHONPATH”
  • “将源根添加到PYTHONPATH”

我已经将run config设置为使用正确的venv,因此PyCharm不需要做其他工作即可向路径添加内容。相反,它导致了错误。

The answer that worked for me was indeed what OP mentions in his 2015 update: uncheck these two boxes in your Python run config:

  • “Add content roots to PYTHONPATH”
  • “Add source roots to PYTHONPATH”

I already had the run config set to use the proper venv, so PyCharm doing additional work to add things to the path was not necessary. Instead it was causing errors.


Python是否具有程序包/模块管理系统?

问题:Python是否具有程序包/模块管理系统?

Python是否具有包/模块管理系统,类似于Ruby在哪里可以使用rubygems gem install packagename

在“ 安装Python模块”上,我仅看到对的引用python setup.py install,但这需要您首先找到该软件包。

Does Python have a package/module management system, similar to how Ruby has rubygems where you can do gem install packagename?

On Installing Python Modules, I only see references to python setup.py install, but that requires you to find the package first.


回答 0

最近的进展

2014年3月:好消息!Pip随附了Python 3.4。Pip长期以来一直是Python的事实上的标准包管理器。您可以这样安装软件包

pip install httpie

哇!这是所有Python版本中的最佳功能。它使每个人都可以访问社区丰富的图书馆。新手不再因设置困难而无法使用社区库。

但是,Python打包经验仍然有许多令人沮丧的地方。累积地,它们使Python对新手来说非常不受欢迎。而且,长期的忽视历史(即从Python 2.0到Python 3.3一直没有使用包管理器交付14年)确实对社区造成了损害。我在下面描述。

突出的挫败感

重要的是要了解,尽管经验丰富的用户能够解决这些问题,但它们却是Python新手的重大障碍。实际上,困难和普遍的用户不友好可能阻止了其中许多人。

PyPI网站是有帮助的

每种带有程序包管理器的语言都有一个官方(或准官方)存储库,供社区下载和发布程序包。Python具有Python包索引PyPI。 https://pypi.python.org/pypi

让我们将其页面与RubyGems和Npm(节点包管理器)的页面进行比较。

  1. https://rubygems.org/gems/rails软件包的RubyGems页面rails
  2. https://www.npmjs.org/package/express软件包的Npm页面express
  3. https://pypi.python.org/pypi/simplejson/软件包的PyPI页面simplejson

您将看到RubyGems和Npm页面均以该程序包的一行说明开始,然后是如何安装的友好说明。

同时,天真地浏览到PyPI的所有不幸的Python用户都会遇到麻烦。在https://pypi.python.org/pypi/simplejson/上,他们找不到任何有用的说明。但是,有一个绿色的大“下载”链接。遵循它并非没有道理。啊哈,他们点击!他们的浏览器下载.tar.gz文件。许多Windows用户甚至无法打开它,但是如果他们坚持不懈,他们最终可能会提取它,然后运行setup.py并最终在Google的帮助下运行setup.py install。有些人会放弃并重新发明轮子。

当然,所有这些都是错误的。安装软件包的最简单方法是使用Pip命令。但是PyPI甚至没有提到Pip。相反,它引导他们走下了一条古老而乏味的道路。

错误:找不到vcvarsall.bat

Numpy是Python最受欢迎的库之一。尝试使用Pip安装它,您会收到以下错误消息:

错误:找不到vcvarsall.bat

尝试解决此问题是Stack Overflow上最受欢迎的问题之一:“ 错误:无法找到vcvarsall.bat

很少有人能成功。

为了进行比较,在相同情况下,Ruby会显示此消息,该消息说明了正在发生的事情以及如何修复它:

请更新您的PATH以包括构建工具,或从http://rubyinstaller.org/downloads下载DevKit 并按照http://github.com/oneclick/rubyinstaller/wiki/Development-Kit上的说明进行操作

发布包很难

Ruby和Nodejs随附功能齐全的软件包管理器Gem(自2007年起)和Npm(自2011年起),并培育了以GitHub为中心的共享社区。Npm使发布软件包就像安装它们一样容易,它已经有64k软件包。RubyGems列出了72k个软件包。古老的Python软件包索引列出41k

历史

面对“ 包含电池 ”的座右铭,直到2014年Python一直没有包装管理器发货。

在Pip之前,事实上的标准是一个命令 easy_install。真是太糟糕了。was no命令用于卸载软件包。

点子是一个巨大的进步。它具有Ruby’s Gem的大多数功能。不幸的是,直到最近,Pip一直很难安装。实际上,该问题仍然是Stack Overflow上最重要的Python问题:“ 如何在Windows上安装pip?

Recent progress

March 2014: Good news! Python 3.4 ships with Pip. Pip has long been Python’s de-facto standard package manager. You can install a package like this:

pip install httpie

Wahey! This is the best feature of any Python release. It makes the community’s wealth of libraries accessible to everyone. Newbies are no longer excluded from using community libraries by the prohibitive difficulty of setup.

However, there remains a number of outstanding frustrations with the Python packaging experience. Cumulatively, they make Python very unwelcoming for newbies. Also, the long history of neglect (ie. not shipping with a package manager for 14 years from Python 2.0 to Python 3.3) did damage to the community. I describe both below.

Outstanding frustrations

It’s important to understand that while experienced users are able to work around these frustrations, they are significant barriers to people new to Python. In fact, the difficulty and general user-unfriendliness is likely to deter many of them.

PyPI website is counter-helpful

Every language with a package manager has an official (or quasi-official) repository for the community to download and publish packages. Python has the Python Package Index, PyPI. https://pypi.python.org/pypi

Let’s compare its pages with those of RubyGems and Npm (the Node package manager).

  1. https://rubygems.org/gems/rails RubyGems page for the package rails
  2. https://www.npmjs.org/package/express Npm page for the package express
  3. https://pypi.python.org/pypi/simplejson/ PyPI page for the package simplejson

You’ll see the RubyGems and Npm pages both begin with a one-line description of the package, then large friendly instructions how to install it.

Meanwhile, woe to any hapless Python user who naively browses to PyPI. On https://pypi.python.org/pypi/simplejson/ , they’ll find no such helpful instructions. There is however, a large green ‘Download’ link. It’s not unreasonable to follow it. Aha, they click! Their browser downloads a .tar.gz file. Many Windows users can’t even open it, but if they persevere they may eventually extract it, then run setup.py and eventually with the help of Google setup.py install. Some will give up and reinvent the wheel..

Of course, all of this is wrong. The easiest way to install a package is with a Pip command. But PyPI didn’t even mention Pip. Instead, it led them down an archaic and tedious path.

Error: Unable to find vcvarsall.bat

Numpy is one of Python’s most popular libraries. Try to install it with Pip, you get this cryptic error message:

Error: Unable to find vcvarsall.bat

Trying to fix that is one of the most popular questions on Stack Overflow: “error: Unable to find vcvarsall.bat

Few people succeed.

For comparison, in the same situation, Ruby prints this message, which explains what’s going on and how to fix it:

Please update your PATH to include build tools or download the DevKit from http://rubyinstaller.org/downloads and follow the instructions at http://github.com/oneclick/rubyinstaller/wiki/Development-Kit

Publishing packages is hard

Ruby and Nodejs ship with full-featured package managers, Gem (since 2007) and Npm (since 2011), and have nurtured sharing communities centred around GitHub. Npm makes publishing packages as easy as installing them, it already has 64k packages. RubyGems lists 72k packages. The venerable Python package index lists only 41k.

History

Flying in the face of its “batteries included” motto, Python shipped without a package manager until 2014.

Until Pip, the de facto standard was a command easy_install. It was woefully inadequate. The was no command to uninstall packages.

Pip was a massive improvement. It had most the features of Ruby’s Gem. Unfortunately, Pip was–until recently–ironically difficult to install. In fact, the problem remains a top Python question on Stack Overflow: “How do I install pip on Windows?


回答 1

Python包索引(PyPI)似乎是标准的:

  • 安装软件包: pip install MyProject
  • 更新pip install --upgrade MyProject
  • 解决一个版本的一揽子pip install MyProject==1.0

您可以如下安装软件包管理器:

curl -O http://python-distribute.org/distribute_setup.py
python distribute_setup.py
easy_install pip

参考文献:

The Python Package Index (PyPI) seems to be standard:

  • To install a package: pip install MyProject
  • To update a package pip install --upgrade MyProject
  • To fix a version of a package pip install MyProject==1.0

You can install the package manager as follows:

curl -O http://python-distribute.org/distribute_setup.py
python distribute_setup.py
easy_install pip

References:


回答 2

只是为了形成对比,还有一点

And just to provide a contrast, there’s also pip.


回答 3

作为Ruby和Perl开发人员和学习Python的人,我还没有发现easy_install或pip等同于RubyGems或CPAN。

当开发人员更新模块时,我倾向于使我的开发系统运行最新版本的模块,并将生产系统冻结为固定版本。RubyGems和CPAN都可以通过列出可用的模块轻松地找到模块,然后进行安装,然后根据需要单独或批量更新。

easy_install和pip使得安装模块变得容易,一旦我通过浏览器搜索找到了它,或者通过其他方法了解了它,但是它们不会告诉我有什么可用。我可以明确命名要更新的模块,但是这些应用程序不会告诉我已更新的内容,也不会在需要时批量更新所有内容。

因此,pip和easy_install中提供了基本功能,但是我希望看到一些缺少的功能,这些功能使它们更友好,更易于使用,并且与CPAN和RubyGems相当。

As a Ruby and Perl developer and learning-Python guy, I haven’t found easy_install or pip to be the equivalent to RubyGems or CPAN.

I tend to keep my development systems running the latest versions of modules as the developers update them, and freeze my production systems at set versions. Both RubyGems and CPAN make it easy to find modules by listing what’s available, then install and later update them individually or in bulk if desired.

easy_install and pip make it easy to install a module ONCE I located it via a browser search or learned about it by some other means, but they won’t tell me what is available. I can explicitly name the module to be updated, but the apps won’t tell me what has been updated nor will they update everything in bulk if I want.

So, the basic functionality is there in pip and easy_install but there are features missing that I’d like to see that would make them friendlier and easier to use and on par with CPAN and RubyGems.


回答 4

至少有两个easy_install及其后继pip

There are at least two, easy_install and its successor pip.


回答 5

至少从2014年下半年开始,应该考虑使用conda软件包管理器的Continuum Analytics的Anaconda Python发行版。一键下载即可解决一般人们在使用Python时遇到的大多数严重问题(管理不同的Python版本,更新Python版本,软件包管理,虚拟环境,Windows / Mac兼容性)。

它使您无需更改系统就可以使用Python完成几乎所有您想做的事情。我的下一个首选解决方案是pip + virtualenv,但是您要么必须将virtualenv安装到系统Python中(并且系统Python可能不是您想要的版本),要么从源代码构建。Anaconda只需单击一个按钮即可完成整个过程,并添加了许多其他功能。

As of at least late 2014, Continuum Analytics’ Anaconda Python distribution with the conda package manager should be considered. It solves most of the serious issues people run into with Python in general (managing different Python versions, updating Python versions, package management, virtual environments, Windows/Mac compatibility) in one cohesive download.

It enables you to do pretty much everything you could want to with Python without having to change the system at all. My next preferred solution is pip + virtualenv, but you either have to install virtualenv into your system Python (and your system Python may not be the version you want), or build from source. Anaconda makes this whole process the click of a button, as well as adding a bunch of other features.


回答 6

那将是easy_install


回答 7

它称为setuptools。您可以使用“ easy_install”命令运行它。

您可以在http://pypi.python.org/中找到该目录

It’s called setuptools. You run it with the “easy_install” command.

You can find the directory at http://pypi.python.org/


回答 8

我在这里没有在其他答案中提到MacPortsHomebrew,但是由于我确实在Stack Overflow的其他地方看到了有关相关问题的提及,因此我会自己添加0.02美元,许多人似乎认为MacPorts不仅是一个软件包软件包管理器(到目前为止,它们列出了16311个软件包/端口,2931个匹配“ python”,尽管仅适用于Mac),但也可以作为Python软件包/模块的不错的(也许更好)的软件包管理器:

“ … Mac python开发人员使用什么方法来管理其模块?”

答案

科学

“ Mac(与Linux不同)没有软件包管理器,但是您可以安装几个流行的软件包管理器。Macports …”

我仍在参数是否自己使用MacPorts,但目前我正朝着这个方向发展。

I don’t see either MacPorts or Homebrew mentioned in other answers here, but since I do see them mentioned elsewhere on Stack Overflow for related questions, I’ll add my own US$0.02 that many folks seem to consider MacPorts as not only a package manager for packages in general (as of today they list 16311 packages/ports, 2931 matching “python”, albeit only for Macs), but also as a decent (maybe better) package manager for Python packages/modules:

Question

“…what is the method that Mac python developers use to manage their modules?”

Answers

SciPy

“Macs (unlike Linux) don’t come with a package manager, but there are a couple of popular package managers you can install. Macports…”

I’m still debating on whether or not to use MacPorts myself, but at the moment I’m leaning in that direction.


回答 9

在Windows上,安装http://chocolatey.org/,然后

choco install python

用更新的PATH打开一个新的cmd窗口。接下来,做

choco install pip

之后,您可以

pip install pyside
pip install ipython
...

On Windows install http://chocolatey.org/ then

choco install python

Open a new cmd-window with the updated PATH. Next, do

choco install pip

After that you can

pip install pyside
pip install ipython
...

回答 10

由于此处没有人提到pipenv,因此我想描述一下我的观点,为什么每个人都应该使用它来管理python软件包。

正如@ColonelPanic所提到的,Python包索引以及pipvirtualenv也存在多个问题。

Pipenv使用pip解决了大多数问题,并且还提供了其他功能。

Pipenv功能

Pipenv旨在取代pip和virtualenv,这意味着Pipenv将自动为每个项目创建一个单独的虚拟环境,从而避免不同项目的不同python版本/软件包版本之间发生冲突。

  • 启用真正的确定性构建,同时轻松地仅指定所需内容。
  • 生成并检查文件散列是否存在锁定的依赖关系。
  • 如果pyenv可用,则自动安装所需的Python。
  • 通过查找Pipfile递归自动找到您的项目主页。
  • 如果不存在,则自动生成一个Pipfile。
  • 在标准位置自动创建virtualenv。
  • 卸载/安装软件包时,会自动将软件包添加/删除到Pipfile中。
  • 自动加载.env文件(如果存在)。

如果您以前从事过python项目,您将意识到这些功能使管理软件包变得更加容易。

其他命令

  • check检查安全漏洞,并断言当前环境已满足PEP 508要求。(我认为这是一个很大的功能,尤其是在此之后-PyPi上的恶意软件包
  • graph 将显示安装的依赖关系的依赖关系图。

您可以在此处阅读更多内容-Pipenv

安装

您可以在此处找到安装文档

PS:如果您喜欢处理Python Package 请求,您将很高兴知道pipenv由同一位开发人员Kenneth Reitz

Since no one has mentioned pipenv here, I would like to describe my views why everyone should use it for managing python packages.

As @ColonelPanic mentioned there are several issues with the Python Package Index and with pip and virtualenv also.

Pipenv solves most of the issues with pip and provides additional features also.

Pipenv features

Pipenv is intended to replace pip and virtualenv, which means pipenv will automatically create a separate virtual environment for every project thus avoiding conflicts between different python versions/package versions for different projects.

  • Enables truly deterministic builds, while easily specifying only what you want.
  • Generates and checks file hashes for locked dependencies.
  • Automatically install required Pythons, if pyenv is available.
  • Automatically finds your project home, recursively, by looking for a Pipfile.
  • Automatically generates a Pipfile, if one doesn’t exist.
  • Automatically creates a virtualenv in a standard location.
  • Automatically adds/removes packages to a Pipfile when they are un/installed.
  • Automatically loads .env files, if they exist.

If you have worked on python projects before, you would realize these features make managing packages way easier.

Other Commands

  • check checks for security vulnerabilities and asserts that PEP 508 requirements are being met by the current environment. (which I think is a great feature especially after this – Malicious packages on PyPi)
  • graph will show you a dependency graph, of your installed dependencies.

You can read more about it here – Pipenv.

Installation

You can find the installation documentation here

P.S.: If you liked working with the Python Package requests , you would be pleased to know that pipenv is by the same developer Kenneth Reitz


回答 11

在2019年,诗歌是您想要的软件包和依赖项管理器。

https://github.com/sdispater/poetry#why

它是现代,简单和可靠的。

In 2019 poetry is the package and dependency manager you are looking for.

https://github.com/sdispater/poetry#why

It’s modern, simple and reliable.


回答 12

诗歌是您要寻找的。它负责依赖管理,虚拟环境和运行。

Poetry is what you’re looking for. It takes care of dependency management, virtual environments, running.


无法在Python中导入我自己的模块

问题:无法在Python中导入我自己的模块

我很难理解模块导入在Python中是如何工作的(我以前从未用任何其他语言来完成过此工作)。

假设我有:

myapp/__init__.py
myapp/myapp/myapp.py
myapp/myapp/SomeObject.py
myapp/tests/TestCase.py

现在,我试图得到这样的东西:

myapp.py
===================
from myapp import SomeObject
# stuff ...

TestCase.py
===================
from myapp import SomeObject
# some tests on SomeObject

但是,我肯定做错了,因为Python看不到这myapp是一个模块:

ImportError: No module named myapp

I’m having a hard time understanding how module importing works in Python (I’ve never done it in any other language before either).

Let’s say I have:

myapp/__init__.py
myapp/myapp/myapp.py
myapp/myapp/SomeObject.py
myapp/tests/TestCase.py

Now I’m trying to get something like this:

myapp.py
===================
from myapp import SomeObject
# stuff ...

TestCase.py
===================
from myapp import SomeObject
# some tests on SomeObject

However, I’m definitely doing something wrong as Python can’t see that myapp is a module:

ImportError: No module named myapp

回答 0

在您的特定情况下,您似乎正在尝试SomeObject从myapp.py和TestCase.py脚本导入。在myapp.py中,执行

import SomeObject

因为它在同一个文件夹中。对于TestCase.py,请执行

from ..myapp import SomeObject

但是,仅当您从软件包中导入TestCase时,此方法才有效。如果要直接运行python TestCase.py,则必须弄乱路径。这可以在Python中完成:

import sys
sys.path.append("..")
from myapp import SomeObject

尽管通常不建议这样做。

通常,如果您希望其他人使用您的Python软件包,则应使用distutils创建安装脚本。这样,任何人都可以使用像这样的命令轻松安装您的软件包,python setup.py install并且该软件包将在其计算机上的所有位置可用。如果您对软件包很认真,甚至可以将其添加到Python软件包索引PyPI中

In your particular case it looks like you’re trying to import SomeObject from the myapp.py and TestCase.py scripts. From myapp.py, do

import SomeObject

since it is in the same folder. For TestCase.py, do

from ..myapp import SomeObject

However, this will work only if you are importing TestCase from the package. If you want to directly run python TestCase.py, you would have to mess with your path. This can be done within Python:

import sys
sys.path.append("..")
from myapp import SomeObject

though that is generally not recommended.

In general, if you want other people to use your Python package, you should use distutils to create a setup script. That way, anyone can install your package easily using a command like python setup.py install and it will be available everywhere on their machine. If you’re serious about the package, you could even add it to the Python Package Index, PyPI.


回答 1

该函数import在PYTHONPATH env中查找文件。变量和您的本地目录。因此,您可以将所有文件放在同一目录中,也可以将键入的路径导出到终端中:

export PYTHONPATH="$PYTHONPATH:/path_to_myapp/myapp/myapp/"

The function import looks for files into your PYTHONPATH env. variable and your local directory. So you can either put all your files in the same directory, or export the path typing into a terminal::

export PYTHONPATH="$PYTHONPATH:/path_to_myapp/myapp/myapp/"

回答 2

导出路径是一个好方法。另一种方法是将.pth添加到您的站点包位置。在我的Mac上,我的python将站点包保存在/ Library / Python中,如下所示

/Library/Python/2.7/site-packages

我在/Library/Python/2.7/site-packages/awesome.pth创建了一个名为awesome.pth的文件,并在文件中放置了以下引用我的超赞模块的路径

/opt/awesome/custom_python_modules

exporting path is a good way. Another way is to add a .pth to your site-packages location. On my mac my python keeps site-packages in /Library/Python shown below

/Library/Python/2.7/site-packages

I created a file called awesome.pth at /Library/Python/2.7/site-packages/awesome.pth and in the file put the following path that references my awesome modules

/opt/awesome/custom_python_modules

回答 3

你可以试试

from myapp.myapp import SomeObject

因为您的项目名称与myapp.py相同,因此它会首先搜索项目文档

You can try

from myapp.myapp import SomeObject

because your project name is the same as the myapp.py which makes it search the project document first


回答 4

在您的第一个myapp目录中,u可以添加setup.py文件,并在setup.py中添加两个python代码

from setuptools import setup
setup(name='myapp')

在命令行的第一个myapp目录中,使用pip install -e。安装软件包

In your first myapp directory ,u can add a setup.py file and add two python code in setup.py

from setuptools import setup
setup(name='myapp')

in your first myapp directory in commandline , use pip install -e . to install the package


回答 5

pip installWindows 10上的默认设置为安装在“ Program Files / PythonXX / Lib / site-packages”中,该目录需要管理权限。因此,我通过以管理员身份运行pip install解决了我的问题 (即使您使用管理员帐户登录,也必须以管理员身份打开命令提示符)。另外,从python调用pip更安全。
例如
python -m pip install <package-name>
代替
pip install <package-name>

pip install on Windows 10 defaults to installing in ‘Program Files/PythonXX/Lib/site-packages’ which is a directory that requires administrative privileges. So I fixed my issue by running pip install as Administrator (you have to open command prompt as administrator even if you are logged in with an admin account). Also, it is safer to call pip from python.
e.g.
python -m pip install <package-name>
instead of
pip install <package-name>


回答 6

就我而言,尽管Windows文件名不区分大小写,但Python导入却使Windows vs Python感到惊讶。因此,如果您有Stuff.py文件,则需要按原样导入此名称。

In my case it was Windows vs Python surprise, despite Windows filenames are not case sensitive, Python import is. So if you have Stuff.py file you need to import this name as-is.


回答 7

你需要

__init__.py

在所有您需要与之交互的代码的文件夹中。即使您尝试导入的文件处于同一级别,也需要在每次导入时指定项目的顶级文件夹名称。

You need to have

__init__.py

in all the folders that have code you need to interact with. You also need to specify the top folder name of your project in every import even if the file you tried to import is at the same level.