如何将第三方模块“包含”到我的python脚本中以使其可移植?

时间:2012-10-14 02:06:51

标签: python

我开发了一个小小的脚本,可以在线搜索壁纸数据库并下载壁纸,我想把这个脚本给另一个用电脑不太好的人,我有点开始使用python所以我不喜欢不知道如何在我的程序中包含第三方模块的“导入”,因此它可以100%移植,是否有什么可以帮助我做到这一点?或者我必须输入并分析我的第三方模块并复制和粘贴我使用的功能?

2 个答案:

答案 0 :(得分:4)

更糟糕的事情

您可以轻松地将其他模块与您的代码捆绑在一起。这样做意味着您应该将其他模块中的函数复制/粘贴到您的代码中 - 您绝对应该这样做,因为您不知道哪些依赖项你会失踪的。您的目录结构可能如下所示:

/myproject
    mycode.py
    thirdpartymodule1.py
    thirdpartymodule2.py
    thirdpartymodule3/
        <contents>

更好的事情

实现此目的的最佳方法是在Python包中包含一个依赖项列表(通常称为requirements.txt),Python的软件包安装程序pip可用于自动下载。由于这可能有点太复杂,你可以给你的朋友这些指示,假设Mac或Linux:

  1. 运行$ curl http://python-distribute.org/distribute_setup.py | python。这为您提供了安装包管理器所需的工具。
  2. 运行$ curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python。这将安装包管理器。
  3. 向您的朋友提供您在代码中使用的第三方Python模块的名称列表。出于此示例的目的,我们会说您使用了requeststwistedboto
  4. 您的朋友应该从命令行$ pip install <list of package names>运行。在我们的示例中,这看起来像$ pip install requests twisted boto
  5. 运行Python代码!像import boto这样的行应该有效,因为你的朋友将在他们的计算机上安装这些包。

答案 1 :(得分:2)

easi(呃)方式:

  1. 以干净的virtual environment开始。
  2. 安装开发代码所需的软件包。
  3. 完成后,为您的项目创建list of requirements
  4. 将此文件(从第3步)发送给您的朋友。
  5. 您的朋友只需pip install -r thefile.txt即可获得您申请的所有要求。

    以下是一个例子:

    D:\>virtualenv --no-site-packages myproject
    The --no-site-packages flag is deprecated; it is now the default behavior.
    New python executable in myproject\Scripts\python.exe
    Installing setuptools................done.
    Installing pip...................done.
    
    D:\>myproject\Scripts\activate.bat
    (myproject) D:\>pip install requests
    Downloading/unpacking requests
      Downloading requests-0.14.1.tar.gz (523Kb): 523Kb downloaded
      Running setup.py egg_info for package requests
    
        warning: no files found matching 'tests\*.'
    Installing collected packages: requests
      Running setup.py install for requests
    
        warning: no files found matching 'tests\*.'
    Successfully installed requests
    Cleaning up...
    
    (myproject) D:\>pip freeze > requirements.txt
    (myproject) D:\>type requirements.txt
    requests==0.14.1