正在从 Github 中导入 python 个库

Importing python libraries from Github

我在 Python 中编写了一些库供我的项目使用。我已将它们本地存储在我的系统上,也已远程存储在 Github 上。现在每次我写一些代码时,我都会在开始时使用 sys.path.append() 来帮助从我的系统目录中导入我的库。我想知道是否可以直接从我的 Github 存储库

导入这些文件

我的回购 link 是这样的 - Quacpy

这感觉有点离谱,但可能适合您(如果您的任何库相互依赖,您也必须将这些导入更改为 githubimports!?):

import requests
def githubimport(user, repo, module):
   d = {}
   url = 'https://raw.githubusercontent.com/{}/{}/master/{}.py'.format(user, repo, module)
   r = requests.get(url).text
   exec(r, d)
   return d

qoperator = githubimport('biryani', 'Quacpy', 'qoperator')

如果您想使用必须安装的存储库,我不确定您希望如何在另一个 python 脚本中自动安装(以及如果安装失败该怎么办)。

但是,如果您只想使用其他文件中的一些方法,您可以下载该文件然后导入它:

import urllib2

def download(url):
    filename = url.split('/')[-1]
    print 'Downloading', filename
    f = urllib2.urlopen(url)
    data = f.read()
    f.close()
    with open(filename, 'w') as myfile:
        myfile.write(data)

# get repository
download('https://raw.githubusercontent.com/biryani/Quacpy/master/auxfun.py')

# try to import something from it
from auxfun import qregnorm
q = qregnorm([0, 1, 2])
print 'Success! q =', q

也许您甚至可以下载整个 zip,解压缩然后导入文件。

假设您有一个有效的 setup.py 文件,pip 支持基于 git 的安装。详情见https://pip.pypa.io/en/latest/reference/pip_install.html#git

剧透:因为你没有 setup.py 文件,如果你当前尝试使用 pip,你会看到以下错误:

pip install -e git+https://github.com/biryani/Quacpy.git#egg=quacpy
Obtaining quacpy from git+https://github.com/biryani/Quacpy.git#egg=quacpy
  Cloning https://github.com/biryani/Quacpy.git to /.../quacpy
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 18, in <module>
    IOError: [Errno 2] No such file or directory: '/.../quacpy/setup.py'

    ----------------------------------------
    Command "python setup.py egg_info" failed with error code 1 in /.../quacpy

这会将整个存储库作为一个模块导入,Python 3:

import sys
import urllib.request # python 3
import zipfile
import os

REPOSITORY_ZIP_URL = 'https://github.com/biryani/Quacpy/archive/master.zip'

filename, headers = urllib.request.urlretrieve(REPOSITORY_ZIP_URL)

zip = zipfile.ZipFile(filename)

directory = filename + '_dir'

zip.extractall(directory)

module_directory_from_zip = os.listdir(directory)[0]
module_directory = 'Quacpy'
os.rename(os.path.join(directory, module_directory_from_zip),
          os.path.join(directory, module_directory))

sys.path.append(directory)

import Quacpy

我在 Colab 中使用的一种解决方法是将文件复制到 Colab 的文件夹,然后将其导入 Python 的解释器。对于您的图书馆,这将是:

!wget -q https://github.com/biryani/Quacpy/__init__.py -O __init__.py > txt.log
from __init__ import *

应该有办法下载整个 repo,必要时解压,然后导入。