标签归档:python-packaging

__init__.py的作用是什么?

问题:__init__.py的作用是什么?

什么是__init__.py一个Python源目录?

What is __init__.py for in a Python source directory?


回答 0

它曾经是软件包的必需部分(旧的3.3之前的“常规软件包”,而不是新的3.3+“命名空间软件包”)。

这是文档。

Python定义了两种类型的程序包,常规程序包和命名空间程序包。常规软件包是Python 3.2及更早版本中存在的传统软件包。常规软件包通常实现为包含__init__.py文件的目录。导入常规程序包时,__init__.py将隐式执行此文件,并将其定义的对象绑定到程序包命名空间中的名称。该__init__.py文件可以包含任何其他模块可以包含的相同Python代码,并且Python在导入时会向该模块添加一些其他属性。

但是只需单击链接,它就会包含一个示例,更多信息以及对命名空间包的说明,这些命名空间包不含__init__.py

It used to be a required part of a package (old, pre-3.3 “regular package”, not newer 3.3+ “namespace package”).

Here’s the documentation.

Python defines two types of packages, regular packages and namespace packages. Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an __init__.py file. When a regular package is imported, this __init__.py file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The __init__.py file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported.

But just click the link, it contains an example, more information, and an explanation of namespace packages, the kind of packages without __init__.py.


回答 1

命名__init__.py的文件用于将磁盘上的目录标记为Python软件包目录。如果您有文件

mydir/spam/__init__.py
mydir/spam/module.py

并且mydir在您的路径上,您可以将代码导入module.py

import spam.module

要么

from spam import module

如果删除该__init__.py文件,Python将不再在该目录中查找子模块,因此尝试导入该模块将失败。

__init__.py文件通常为空,但可用于以更方便的名称导出包的选定部分,保留方便的功能等。给定上面的示例,可以按以下方式访问init模块的内容:

import spam

基于

Files named __init__.py are used to mark directories on disk as Python package directories. If you have the files

mydir/spam/__init__.py
mydir/spam/module.py

and mydir is on your path, you can import the code in module.py as

import spam.module

or

from spam import module

If you remove the __init__.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.

The __init__.py file is usually empty, but can be used to export selected portions of the package under more convenient name, hold convenience functions, etc. Given the example above, the contents of the init module can be accessed as

import spam

based on this


回答 2

除了将目录标记为Python软件包并定义之外__all__,还__init__.py允许您在软件包级别定义任何变量。如果程序包定义了将以类似于API的方式频繁导入的内容,则这样做通常很方便。这种模式促进了对Pythonic的“扁平优于嵌套”哲学的坚持。

一个例子

这是我的一个项目的示例,在该项目中,我经常导入sessionmaker被叫Session以与数据库交互。我写了一个带有一些模块的“数据库”包:

database/
    __init__.py
    schema.py
    insertions.py
    queries.py

__init__.py包含以下代码:

import os

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

engine = create_engine(os.environ['DATABASE_URL'])
Session = sessionmaker(bind=engine)

既然我Session在这里定义,就可以使用以下语法开始新的会话。此代码将从“数据库”包目录的内部或外部执行相同。

from database import Session
session = Session()

当然,这是一个小方便—替代方法是Session在数据库包中的新文件(例如“ create_session.py”)中定义,然后使用以下命令启动新会话:

from database.create_session import Session
session = Session()

进一步阅读

有一个非常有趣的reddit线程,涵盖了__init__.py此处的适当用法:

http://www.reddit.com/r/Python/comments/1bbbwk/whats_your_opinion_on_what_to_include_in_init_py/

大多数人似乎认为__init__.py文件应该非常薄,以避免违反“显式优于隐式”的哲学。

In addition to labeling a directory as a Python package and defining __all__, __init__.py allows you to define any variable at the package level. Doing so is often convenient if a package defines something that will be imported frequently, in an API-like fashion. This pattern promotes adherence to the Pythonic “flat is better than nested” philosophy.

An example

Here is an example from one of my projects, in which I frequently import a sessionmaker called Session to interact with my database. I wrote a “database” package with a few modules:

database/
    __init__.py
    schema.py
    insertions.py
    queries.py

My __init__.py contains the following code:

import os

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

engine = create_engine(os.environ['DATABASE_URL'])
Session = sessionmaker(bind=engine)

Since I define Session here, I can start a new session using the syntax below. This code would be the same executed from inside or outside of the “database” package directory.

from database import Session
session = Session()

Of course, this is a small convenience — the alternative would be to define Session in a new file like “create_session.py” in my database package, and start new sessions using:

from database.create_session import Session
session = Session()

Further reading

There is a pretty interesting reddit thread covering appropriate uses of __init__.py here:

http://www.reddit.com/r/Python/comments/1bbbwk/whats_your_opinion_on_what_to_include_in_init_py/

The majority opinion seems to be that __init__.py files should be very thin to avoid violating the “explicit is better than implicit” philosophy.


回答 3

有两个主要原因 __init__.py

  1. 为方便起见:其他用户将不需要知道您的函数在包层次结构中的确切位置。

    your_package/
      __init__.py
      file1.py
      file2.py
        ...
      fileN.py
    # in __init__.py
    from file1 import *
    from file2 import *
    ...
    from fileN import *
    # in file1.py
    def add():
        pass

    然后其他人可以通过以下方式调用add()

    from your_package import add

    不知道file1,例如

    from your_package.file1 import add
  2. 如果您想初始化一些东西;例如,日志记录(应放在顶层):

    import logging.config
    logging.config.dictConfig(Your_logging_config)

There are 2 main reasons for __init__.py

  1. For convenience: the other users will not need to know your functions’ exact location in your package hierarchy.

    your_package/
      __init__.py
      file1.py
      file2.py
        ...
      fileN.py
    
    # in __init__.py
    from file1 import *
    from file2 import *
    ...
    from fileN import *
    
    # in file1.py
    def add():
        pass
    

    then others can call add() by

    from your_package import add
    

    without knowing file1, like

    from your_package.file1 import add
    
  2. If you want something to be initialized; for example, logging (which should be put in the top level):

    import logging.config
    logging.config.dictConfig(Your_logging_config)
    

回答 4

__init__.py文件使Python将包含它的目录视为模块。

此外,这是要在模块中加载的第一个文件,因此您可以使用它来执行每次加载模块时要运行的代码,或指定要导出的子模块。

The __init__.py file makes Python treat directories containing it as modules.

Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.


回答 5

从Python 3.3开始,__init__.py不再需要将目录定义为可导入的Python包。

检查PEP 420:隐式命名空间包

对不需要__init__.py标记文件并且可以自动跨越多个路径段的软件包目录的本地支持(受PEP 420中所述的各种第三方方法启发,用于命名空间软件包)

这是测试:

$ mkdir -p /tmp/test_init
$ touch /tmp/test_init/module.py /tmp/test_init/__init__.py
$ tree -at /tmp/test_init
/tmp/test_init
├── module.py
└── __init__.py
$ python3

>>> import sys
>>> sys.path.insert(0, '/tmp')
>>> from test_init import module
>>> import test_init.module

$ rm -f /tmp/test_init/__init__.py
$ tree -at /tmp/test_init
/tmp/test_init
└── module.py
$ python3

>>> import sys
>>> sys.path.insert(0, '/tmp')
>>> from test_init import module
>>> import test_init.module

参考:
https
: //docs.python.org/3/whatsnew/3.3.html#pep-420-implicit-namespace-packages https://www.python.org/dev/peps/pep-0420/
是__init__。 py对于Python 3中的软件包不是必需的?

Since Python 3.3, __init__.py is no longer required to define directories as importable Python packages.

Check PEP 420: Implicit Namespace Packages:

Native support for package directories that don’t require __init__.py marker files and can automatically span multiple path segments (inspired by various third party approaches to namespace packages, as described in PEP 420)

Here’s the test:

$ mkdir -p /tmp/test_init
$ touch /tmp/test_init/module.py /tmp/test_init/__init__.py
$ tree -at /tmp/test_init
/tmp/test_init
├── module.py
└── __init__.py
$ python3

>>> import sys
>>> sys.path.insert(0, '/tmp')
>>> from test_init import module
>>> import test_init.module

$ rm -f /tmp/test_init/__init__.py
$ tree -at /tmp/test_init
/tmp/test_init
└── module.py
$ python3

>>> import sys
>>> sys.path.insert(0, '/tmp')
>>> from test_init import module
>>> import test_init.module

references:
https://docs.python.org/3/whatsnew/3.3.html#pep-420-implicit-namespace-packages
https://www.python.org/dev/peps/pep-0420/
Is __init__.py not required for packages in Python 3?


回答 6

在Python中,包的定义非常简单。像Java一样,层次结构和目录结构相同。但是您必须将__init__.py其打包。我将__init__.py用以下示例解释该文件:

package_x/
|--  __init__.py
|--    subPackage_a/
|------  __init__.py
|------  module_m1.py
|--    subPackage_b/
|------  __init__.py
|------  module_n1.py
|------  module_n2.py
|------  module_n3.py

__init__.py只要存在就可以为空。它指示该目录应视为一个包。当然__init__.py也可以设置适当的内容。

如果我们在module_n1中添加一个函数:

def function_X():
    print "function_X in module_n1"
    return

运行后:

>>>from package_x.subPackage_b.module_n1 import function_X
>>>function_X()

function_X in module_n1 

然后,我们遵循层次结构包,并将module_n1称为函数。我们可以__init__.py像这样在subPackage_b中使用:

__all__ = ['module_n2', 'module_n3']

运行后:

>>>from package_x.subPackage_b import * 
>>>module_n1.function_X()

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named module_n1

因此,使用*导入,模块包受__init__.py内容的约束。

In Python the definition of package is very simple. Like Java the hierarchical structure and the directory structure are the same. But you have to have __init__.py in a package. I will explain the __init__.py file with the example below:

package_x/
|--  __init__.py
|--    subPackage_a/
|------  __init__.py
|------  module_m1.py
|--    subPackage_b/
|------  __init__.py
|------  module_n1.py
|------  module_n2.py
|------  module_n3.py

__init__.py can be empty, as long as it exists. It indicates that the directory should be regarded as a package. Of course, __init__.py can also set the appropriate content.

If we add a function in module_n1:

def function_X():
    print "function_X in module_n1"
    return

After running:

>>>from package_x.subPackage_b.module_n1 import function_X
>>>function_X()

function_X in module_n1 

Then we followed the hierarchy package and called module_n1 the function. We can use __init__.py in subPackage_b like this:

__all__ = ['module_n2', 'module_n3']

After running:

>>>from package_x.subPackage_b import * 
>>>module_n1.function_X()

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named module_n1

Hence using * importing, module package is subject to __init__.py content.


回答 7

尽管Python在没有__init__.py文件的情况下仍可工作,但您仍应包含一个文件。

它指定应将程序包视为模块,因此将其包括在内(即使它为空)。

在某些情况下,您实际上可能会使用__init__.py文件:

假设您具有以下文件结构:

main_methods 
    |- methods.py

methods.py包含以下内容:

def foo():
    return 'foo'

要使用,foo()您需要以下条件之一:

from main_methods.methods import foo # Call with foo()
from main_methods import methods # Call with methods.foo()
import main_methods.methods # Call with main_methods.methods.foo()

也许您需要(或想要)保留methods.py在内部main_methods(例如,运行时/依赖项),但只想导入main_methods


如果将的名称更改为methods.py__init__.pyfoo()只需导入即可使用main_methods

import main_methods
print(main_methods.foo()) # Prints 'foo'

这是有效的,因为__init__.py它被视为包装的一部分。


一些Python软件包实际上是这样做的。以JSON为例,其中running import json实际上是__init__.pyjson包中导入的(请参阅此处的包文件结构):

源代码: Lib/json/__init__.py

Although Python works without an __init__.py file you should still include one.

It specifies a package should be treated as a module, so therefore include it (even if it is empty).

There is also a case where you may actually use an __init__.py file:

Imagine you had the following file structure:

main_methods 
    |- methods.py

And methods.py contained this:

def foo():
    return 'foo'

To use foo() you would need one of the following:

from main_methods.methods import foo # Call with foo()
from main_methods import methods # Call with methods.foo()
import main_methods.methods # Call with main_methods.methods.foo()

Maybe there you need (or want) to keep methods.py inside main_methods (runtimes/dependencies for example) but you only want to import main_methods.


If you changed the name of methods.py to __init__.py then you could use foo() by just importing main_methods:

import main_methods
print(main_methods.foo()) # Prints 'foo'

This works because __init__.py is treated as part of the package.


Some Python packages actually do this. An example is with JSON, where running import json is actually importing __init__.py from the json package (see the package file structure here):

Source code: Lib/json/__init__.py


回答 8

__init__.py 会将其所在目录视为可加载模块。

对于喜欢阅读代码的人,我在这里添加了两位炼金术士的评论。

$ find /tmp/mydir/
/tmp/mydir/
/tmp/mydir//spam
/tmp/mydir//spam/__init__.py
/tmp/mydir//spam/module.py
$ cd ~
$ python
>>> import sys
>>> sys.path.insert(0, '/tmp/mydir')
>>> from spam import module
>>> module.myfun(3)
9
>>> exit()
$ 
$ rm /tmp/mydir/spam/__init__.py*
$ 
$ python
>>> import sys
>>> sys.path.insert(0, '/tmp/mydir')
>>> from spam import module
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named spam
>>> 

__init__.py will treat the directory it is in as a loadable module.

For people who prefer reading code, I put Two-Bit Alchemist’s comment here.

$ find /tmp/mydir/
/tmp/mydir/
/tmp/mydir//spam
/tmp/mydir//spam/__init__.py
/tmp/mydir//spam/module.py
$ cd ~
$ python
>>> import sys
>>> sys.path.insert(0, '/tmp/mydir')
>>> from spam import module
>>> module.myfun(3)
9
>>> exit()
$ 
$ rm /tmp/mydir/spam/__init__.py*
$ 
$ python
>>> import sys
>>> sys.path.insert(0, '/tmp/mydir')
>>> from spam import module
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named spam
>>> 

回答 9

它有助于导入其他python文件。当您将此文件放置在包含其他py文件的目录中(例如,东西)时,可以执行诸如import stuff.other之类的操作。

root\
    stuff\
         other.py

    morestuff\
         another.py

如果__init__.py在目录东西中没有此内容,则无法导入other.py,因为Python不知道东西的源代码在哪里,也无法将其识别为包。

It facilitates importing other python files. When you placed this file in a directory (say stuff)containing other py files, then you can do something like import stuff.other.

root\
    stuff\
         other.py

    morestuff\
         another.py

Without this __init__.py inside the directory stuff, you couldn’t import other.py, because Python doesn’t know where the source code for stuff is and unable to recognize it as a package.


回答 10

一个__init__.py文件使得进口容易。当__init__.py包中包含an时,a()可以从文件中导入函数,b.py如下所示:

from b import a

但是,没有它,您将无法直接导入。您必须修改系统路径:

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

from b import a

An __init__.py file makes imports easy. When an __init__.py is present within a package, function a() can be imported from file b.py like so:

from b import a

Without it, however, you can’t import directly. You have to amend the system path:

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

from b import a

什么是setup.py?

问题:什么是setup.py?

谁能解释一下setup.py它是什么以及如何进行配置或使用?

Can anyone please explain what setup.py is and how it can be configured or used?


回答 0

setup.py 是一个python文件,通常会告诉您要安装的模块/软件包已与Distutils打包并分发,Distutils是分发Python模块的标准。

这使您可以轻松安装Python软件包。通常写就足够了:

$ pip install . 

pip将使用setup.py安装模块。避免setup.py直接调用。

https://docs.python.org/3/installing/index.html#installing-index

setup.py is a python file, which usually tells you that the module/package you are about to install has been packaged and distributed with Distutils, which is the standard for distributing Python Modules.

This allows you to easily install Python packages. Often it’s enough to write:

$ pip install . 

pip will use setup.py to install your module. Avoid calling setup.py directly.

https://docs.python.org/3/installing/index.html#installing-index


回答 1

它有助于foo在您的计算机上安装python软件包(也可以位于中virtualenv),以便您可以foo从其他项目以及[I] Python提示符中导入该软件包。

它完成pipeasy_install等的类似工作,


使用 setup.py

让我们从一些定义开始:

-包含__init__.py文件的文件夹/目录。
模块 -具有.py扩展名的有效python文件。
分发 -一个软件包与其他软件包模块的关系

假设您要安装名为的软件包foo。那你做

$ git clone https://github.com/user/foo  
$ cd foo
$ python setup.py install

相反,如果您不想实际安装它,但仍然想使用它。然后做,

$ python setup.py develop  

此命令将在站点包内创建到源目录的符号链接,而不是复制内容。因此,它非常快(特别是对于大包装)。


创造 setup.py

如果您有类似的打包树,

foo
├── foo
   ├── data_struct.py
   ├── __init__.py
   └── internals.py
├── README
├── requirements.txt
└── setup.py

然后,在setup.py脚本中执行以下操作,以便可以将其安装在某些计算机上:

from setuptools import setup

setup(
   name='foo',
   version='1.0',
   description='A useful module',
   author='Man Foo',
   author_email='foomail@foo.com',
   packages=['foo'],  #same as name
   install_requires=['bar', 'greek'], #external packages as dependencies
)

相反,如果您的程序包树更复杂,如以下所示:

foo
├── foo
   ├── data_struct.py
   ├── __init__.py
   └── internals.py
├── README
├── requirements.txt
├── scripts
   ├── cool
   └── skype
└── setup.py

然后,setup.py在这种情况下,您将像:

from setuptools import setup

setup(
   name='foo',
   version='1.0',
   description='A useful module',
   author='Man Foo',
   author_email='foomail@foo.com',
   packages=['foo'],  #same as name
   install_requires=['bar', 'greek'], #external packages as dependencies
   scripts=[
            'scripts/cool',
            'scripts/skype',
           ]
)

向(setup.py)添加更多内容,并使其得体:

from setuptools import setup

with open("README", 'r') as f:
    long_description = f.read()

setup(
   name='foo',
   version='1.0',
   description='A useful module',
   license="MIT",
   long_description=long_description,
   author='Man Foo',
   author_email='foomail@foo.com',
   url="http://www.foopackage.com/",
   packages=['foo'],  #same as name
   install_requires=['bar', 'greek'], #external packages as dependencies
   scripts=[
            'scripts/cool',
            'scripts/skype',
           ]
)

long_description被使用pypi.org作为你的包的README描述。


最后,您现在可以将软件包上传到PyPi.org,以便其他人可以使用来安装您的软件包pip install yourpackage

第一步是使用以下方法在pypi中声明您的软件包名称和空间:

$ python setup.py register

注册您的包裹名称后,任何人都无法声明或使用它。成功注册后,您必须通过以下方式将软件包上传到云(到云):

$ python setup.py upload

您也可以选择GPG通过以下方式对包裹进行签名:

$ python setup.py --sign upload

奖励setup.py在此处查看来自真实项目的示例:torchvision-setup.py

It helps to install a python package foo on your machine (can also be in virtualenv) so that you can import the package foo from other projects and also from [I]Python prompts.

It does the similar job of pip, easy_install etc.,


Using setup.py

Let’s start with some definitions:

Package – A folder/directory that contains __init__.py file.
Module – A valid python file with .py extension.
Distribution – How one package relates to other packages and modules.

Let’s say you want to install a package named foo. Then you do,

$ git clone https://github.com/user/foo  
$ cd foo
$ python setup.py install

Instead, if you don’t want to actually install it but still would like to use it. Then do,

$ python setup.py develop  

This command will create symlinks to the source directory within site-packages instead of copying things. Because of this, it is quite fast (particularly for large packages).


Creating setup.py

If you have your package tree like,

foo
├── foo
│   ├── data_struct.py
│   ├── __init__.py
│   └── internals.py
├── README
├── requirements.txt
└── setup.py

Then, you do the following in your setup.py script so that it can be installed on some machine:

from setuptools import setup

setup(
   name='foo',
   version='1.0',
   description='A useful module',
   author='Man Foo',
   author_email='foomail@foo.com',
   packages=['foo'],  #same as name
   install_requires=['bar', 'greek'], #external packages as dependencies
)

Instead, if your package tree is more complex like the one below:

foo
├── foo
│   ├── data_struct.py
│   ├── __init__.py
│   └── internals.py
├── README
├── requirements.txt
├── scripts
│   ├── cool
│   └── skype
└── setup.py

Then, your setup.py in this case would be like:

from setuptools import setup

setup(
   name='foo',
   version='1.0',
   description='A useful module',
   author='Man Foo',
   author_email='foomail@foo.com',
   packages=['foo'],  #same as name
   install_requires=['bar', 'greek'], #external packages as dependencies
   scripts=[
            'scripts/cool',
            'scripts/skype',
           ]
)

Add more stuff to (setup.py) & make it decent:

from setuptools import setup

with open("README", 'r') as f:
    long_description = f.read()

setup(
   name='foo',
   version='1.0',
   description='A useful module',
   license="MIT",
   long_description=long_description,
   author='Man Foo',
   author_email='foomail@foo.com',
   url="http://www.foopackage.com/",
   packages=['foo'],  #same as name
   install_requires=['bar', 'greek'], #external packages as dependencies
   scripts=[
            'scripts/cool',
            'scripts/skype',
           ]
)

The long_description is used in pypi.org as the README description of your package.


And finally, you’re now ready to upload your package to PyPi.org so that others can install your package using pip install yourpackage.

First step is to claim your package name & space in pypi using:

$ python setup.py register

Once your package name is registered, nobody can claim or use it. After successful registration, you have to upload your package there (to the cloud) by,

$ python setup.py upload

Optionally, you can also sign your package with GPG by,

$ python setup.py --sign upload

Bonus: See a sample setup.py from a real project here: torchvision-setup.py


回答 2

setup.py是Python对多平台安装程序和make文件的解答。

如果您熟悉命令行安装,请make && make install转换为python setup.py build && python setup.py install

一些软件包是纯Python,并且仅按字节编译。其他可能包含本机代码,这将需要本机编译器(如gcccl)和Python接口模块(如swigpyrex)。

setup.py is Python’s answer to a multi-platform installer and make file.

If you’re familiar with command line installations, then make && make install translates to python setup.py build && python setup.py install.

Some packages are pure Python, and are only byte compiled. Others may contain native code, which will require a native compiler (like gcc or cl) and a Python interfacing module (like swig or pyrex).


回答 3

如果您下载的软件包在根文件夹中具有“ setup.py”,则可以通过运行以下命令进行安装

python setup.py install

如果您正在开发项目,并且想知道此文件的用途,请查看有关编写安装脚本的Python文档。

If you downloaded package that has “setup.py” in root folder, you can install it by running

python setup.py install

If you are developing a project and are wondering what this file is useful for, check Python documentation on writing the Setup Script


回答 4

setup.py是通常用该语言编写的库或程序随附的Python脚本。目的是正确安装软件。

许多软件包将distutils框架与结合使用setup.py

http://docs.python.org/distutils/

setup.py is a Python script that is usually shipped with libraries or programs, written in that language. It’s purpose is the correct installation of the software.

Many packages use the distutils framework in conjuction with setup.py.

http://docs.python.org/distutils/


回答 5

setup.py可以在两种情况下使用:首先,您要安装Python软件包。其次,您要创建自己的Python包。通常,标准的Python软件包具有几个重要文件,例如setup.py,setup.cfg和Manifest.in。当您创建Python软件包时,这三个文件将确定(egg-info文件夹下PKG-INFO中的内容)名称,版本,描述,其他所需的安装(通常在.txt文件中)以及其他几个参数。创建包时setup.py将读取setup.cfg(可以是tar.gz)。在Manifest.in中,您可以定义应包含在软件包中的内容。无论如何,您都可以使用setup.py做很多事情,例如

python setup.py build
python setup.py install
python setup.py sdist <distname> upload [-r urltorepo]  (to upload package to pypi or local repo)

还有许多其他命令可以与setup.py一起使用。求助

python setup.py --help-commands

setup.py can be used in two scenarios , First, you want to install a Python package. Second, you want to create your own Python package. Usually standard Python package has couple of important files like setup.py, setup.cfg and Manifest.in. When you are creating the Python package, these three files will determine the (content in PKG-INFO under egg-info folder) name, version, description, other required installations (usually in .txt file) and few other parameters. setup.cfg is read by setup.py while package is created (could be tar.gz ). Manifest.in is where you can define what should be included in your package. Anyways you can do bunch of stuff using setup.py like

python setup.py build
python setup.py install
python setup.py sdist <distname> upload [-r urltorepo]  (to upload package to pypi or local repo)

There are bunch of other commands which could be used with setup.py . for help

python setup.py --help-commands

回答 6

当您通过setup.py打开终端(Mac,Linux)或命令提示符(Windows)下载软件包时。使用“ cd Tab”按钮并为您提供帮助,将路径设置为已下载文件的文件夹的正确位置,该文​​件夹位于setup.py

iMac:~ user $ cd path/pakagefolderwithsetupfile/

按Enter键,您应该会看到类似以下内容:

iMac:pakagefolderwithsetupfile user$

然后输入以下内容python setup.py install

iMac:pakagefolderwithsetupfile user$ python setup.py install

enter。做完了!

When you download a package with setup.py open your Terminal (Mac,Linux) or Command Prompt (Windows). Using cd and helping you with Tab button set the path right to the folder where you have downloaded the file and where there is setup.py :

iMac:~ user $ cd path/pakagefolderwithsetupfile/

Press enter, you should see something like this:

iMac:pakagefolderwithsetupfile user$

Then type after this python setup.py install :

iMac:pakagefolderwithsetupfile user$ python setup.py install

Press enter. Done!


回答 7

要安装已下载的Python软件包,请提取档案并在其中运行setup.py脚本:

python setup.py install

对我来说,这一直很奇怪。将包管理器指向下载位置会更自然,例如在Ruby和Nodejs中。gem install rails-4.1.1.gem

包管理器也更舒适,因为它既熟悉又可靠。另一方面,每个setup.py都是新颖的,因为它是特定于包装的。它要求遵守约定“我相信此setup.py会接受与过去使用的命令相同的命令”。这是对精神意志力的遗憾。

我并不是说setup.py工作流的安全性不如包管理器(我知道Pip只是在内部运行setup.py),但是我肯定觉得这很麻烦。将所有命令都发送到同一个程序包管理器应用程序是一种和谐。您甚至可能会喜欢它。

To install a Python package you’ve downloaded, you extract the archive and run the setup.py script inside:

python setup.py install

To me, this has always felt odd. It would be more natural to point a package manager at the download, as one would do in Ruby and Nodejs, eg. gem install rails-4.1.1.gem

A package manager is more comfortable too, because it’s familiar and reliable. On the other hand, each setup.py is novel, because it’s specific to the package. It demands faith in convention “I trust this setup.py takes the same commands as others I have used in the past”. That’s a regrettable tax on mental willpower.

I’m not saying the setup.py workflow is less secure than a package manager (I understand Pip just runs the setup.py inside), but certainly I feel it’s awkard and jarring. There’s a harmony to commands all being to the same package manager application. You might even grow fond it.


回答 8

setup.py是与其他文件一样的Python文件。它可以采用任何名称,除非按惯例命名,否则setup.py每个脚本都没有不同的过程。

最常setup.py用于安装Python模块,但用于服务器其他目的:

模块:

也许这是setup.py模块中最著名的用法。尽管可以使用来安装它们pip,但pip默认情况下不包括旧的Python版本,因此需要单独安装。

如果您想安装模块但不想安装pip,则唯一的选择是从setup.py文件安装模块。这可以通过完成python setup.py install。这将Python模块安装到根字典(不pipeasy_installECT)。

pip失败时通常使用此方法。例如,如果所需软件包的正确Python版本pip由于可能由于不再维护而无法提供,则下载源并运行python setup.py install将执行相同的操作,除非需要编译的二进制文件(但将忽略编译的二进制文件)。 Python版本-除非返回错误)。

的另一种用法setup.py是从源代码安装软件包。如果模块仍在开发中,则将无法使用wheel文件,并且唯一的安装方法是直接从源代码进行安装。

构建Python扩展:

构建模块后,可以使用distutils安装脚本将其转换为可分发的模块。一旦构建完成,就可以使用上面的命令进行安装。

安装脚本易于构建,一旦文件已正确配置并且可以通过运行进行编译python setup.py build(请参阅所有命令的链接)。

再次setup.py按易用性和惯例命名,但可以使用任何名称。

Cython:

setup.py文件的另一种著名用法包括编译后的扩展名。这些需要具有用户定义值的安装脚本。它们允许快速执行(但一旦编译则依赖平台)。这是文档中的一个简单示例:

from distutils.core import setup
from Cython.Build import cythonize

setup(
    name = 'Hello world app',
    ext_modules = cythonize("hello.pyx"),
)

这可以通过编译 python setup.py build

Cx_Freeze:

需要安装脚本的另一个模块是cx_Freeze。这会将Python脚本转换为可执行文件。这允许包括描述,名称,图标,包在内的许多命令包括,排除等,并且一旦运行将产生可分发的应用程序。文档中的示例:

import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]} 

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(  name = "guifoo",
        version = "0.1",
        description = "My GUI application!",
        options = {"build_exe": build_exe_options},
        executables = [Executable("guifoo.py", base=base)])

可以通过编译python setup.py build

那么什么是setup.py文件?

很简单,它是一个在Python环境中构建或配置某些东西的脚本。

分发时,程序包应仅包含一个安装脚本,但将多个脚本组合成一个安装脚本并不少见。请注意,这经常涉及distutils但并非总是如此(如我在上一个示例中所示)。要记住的事情是以某种方式配置Python包/脚本。

它使用名称,因此在构建或安装时始终可以使用相同的命令。

setup.py is a Python file like any other. It can take any name, except by convention it is named setup.py so that there is not a different procedure with each script.

Most frequently setup.py is used to install a Python module but server other purposes:

Modules:

Perhaps this is most famous usage of setup.py is in modules. Although they can be installed using pip, old Python versions did not include pip by default and they needed to be installed separately.

If you wanted to install a module but did not want to install pip, just about the only alternative was to install the module from setup.py file. This could be achieved via python setup.py install. This would install the Python module to the root dictionary (without pip, easy_install ect).

This method is often used when pip will fail. For example if the correct Python version of the desired package is not available via pipperhaps because it is no longer maintained, , downloading the source and running python setup.py install would perform the same thing, except in the case of compiled binaries are required, (but will disregard the Python version -unless an error is returned).

Another use of setup.py is to install a package from source. If a module is still under development the wheel files will not be available and the only way to install is to install from the source directly.

Building Python extensions:

When a module has been built it can be converted into module ready for distribution using a distutils setup script. Once built these can be installed using the command above.

A setup script is easy to build and once the file has been properly configured and can be compiled by running python setup.py build (see link for all commands).

Once again it is named setup.py for ease of use and by convention, but can take any name.

Cython:

Another famous use of setup.py files include compiled extensions. These require a setup script with user defined values. They allow fast (but once compiled are platform dependant) execution. Here is a simple example from the documentation:

from distutils.core import setup
from Cython.Build import cythonize

setup(
    name = 'Hello world app',
    ext_modules = cythonize("hello.pyx"),
)

This can be compiled via python setup.py build

Cx_Freeze:

Another module requiring a setup script is cx_Freeze. This converts Python script to executables. This allows many commands such as descriptions, names, icons, packages to include, exclude ect and once run will produce a distributable application. An example from the documentation:

import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]} 

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(  name = "guifoo",
        version = "0.1",
        description = "My GUI application!",
        options = {"build_exe": build_exe_options},
        executables = [Executable("guifoo.py", base=base)])

This can be compiled via python setup.py build.

So what is a setup.py file?

Quite simply it is a script that builds or configures something in the Python environment.

A package when distributed should contain only one setup script but it is not uncommon to combine several together into a single setup script. Notice this often involves distutils but not always (as I showed in my last example). The thing to remember it just configures Python package/script in some way.

It takes the name so the same command can always be used when building or installing.


回答 9

为简单起见,setup.py的运行就像"__main__"您在调用安装函数时提到的其他答案一样。在setup.py内部,应该放置安装软件包所需的一切。

常用的setup.py功能

以下两节讨论了许多setup.py模块具有的两件事。

setuptools.setup

此功能允许您指定项目属性,例如项目的名称,版本。…最重要的是,如果其他功能打包正确,此功能将允许您安装其他功能。请参阅此网页以获取setuptools.setup的示例。setuptools.setup的

这些属性允许安装以下类型的软件包:

自定义功能

在理想的世界中,setuptools.setup将为您处理所有事情。不幸的是,情况并非总是如此。有时,您需要做一些特定的事情,例如使用subprocess命令安装依赖项,以使要安装的系统处于正确的软件包状态。尝试避免这种情况,这些功能会造成混乱,并且在OS甚至发行版之间通常会有所不同。

To make it simple, setup.py is run as "__main__" when you call the install functions the other answers mentioned. Inside setup.py, you should put everything needed to install your package.

Common setup.py functions

The following two sections discuss two things many setup.py modules have.

setuptools.setup

This function allows you to specify project attributes like the name of the project, the version…. Most importantly, this function allows you to install other functions if they’re packaged properly. See this webpage for an example of setuptools.setup

These attributes of setuptools.setup enable installing these types of packages:

  • Packages that are imported to your project and listed in PyPI using setuptools.findpackages:

    packages=find_packages(exclude=["docs","tests", ".gitignore", "README.rst","DESCRIPTION.rst"])

  • Packages not in PyPI, but can be downloaded from a URL using dependency_links

    dependency_links=["http://peak.telecommunity.com/snapshots/",]

Custom functions

In an ideal world, setuptools.setup would handle everything for you. Unfortunately this isn’t always the case. Sometimes you have to do specific things, like installing dependencies with the subprocess command, to get the system you’re installing on in the right state for your package. Try to avoid this, these functions get confusing and often differ between OS and even distribution.