簡體   English   中英

如何將第三方模塊“包含”到我的python腳本中以使其可移植?

[英]How to “include” third party modules into my python script to make it portable?

我開發了一個小腳本,在網上搜索壁紙數據庫並下載壁紙,我想把這個腳本給另一個不太適合電腦的人,我有點開始用python所以我不知道如何在我的程序中包含第三方模塊的“導入”,以便它可以100%移植,是否有什么可以幫助我這樣做? 或者我將不得不輸入和分析我的第三方模塊並復制和粘貼我使用的功能?

更糟糕的事情要做

您可以輕松地將其他模塊與您的代碼捆綁在一起。 並不意味着你應該復制/從其他模塊的功能,粘貼到你的代碼-你絕對應該這樣做,因為你不知道什么是依賴關系,你會丟失。 您的目錄結構可能如下所示:

/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 $ curl http://python-distribute.org/distribute_setup.py | python 這為您提供了安裝包管理器所需的工具。
  2. 運行$ curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python $ 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這樣的行應該可以工作,因為你的朋友將在他們的計算機上安裝這些包。

easi(呃)方式:

  1. 從干凈的虛擬環境開始
  2. 安裝開發代碼所需的軟件包。
  3. 完成后,創建項目的需求列表
  4. 將此文件(從第3步)發送給您的朋友。

你的朋友只需要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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM