Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a Python module be imported from a URL?

Tags:

As an experiment, I want to see how to import a Python module from a URL. The hypothetical goal here would be to import from a central location which keeps the modules up-to-date. How could this be done?

My attempt is as follows:

>>> import urllib >>>  >>> def import_URL(URL): ...     exec urllib.urlopen(URL) in globals() ...  >>> import_URL("https://cdn.rawgit.com/wdbm/shijian/master/shijian.py") Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "<stdin>", line 2, in import_URL TypeError: exec: arg 1 must be a string, file, or code object 

EDIT: Martijn Pieters identified a fix for the example code that results in the string representation of the remote module. The resulting code is as follows:

import urllib def import_URL(URL):     exec urllib.urlopen(URL).read() in globals() 
like image 526
d3pd Avatar asked Feb 03 '15 14:02

d3pd


People also ask

How are modules imported in Python?

Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.

How do I open a url in Python?

just open the python interpreter and type webbrowser. open('http://www.google.com') and see if it does what you want. yes. The result is same.


2 Answers

Basically there is a module exactly for this purpose called httpimport. Currently it supports importing from a URL that contains the package/module and also from archives (.tar.*, .zip) that can be found in URLs (this is a way to handle remote dependencies).

It is fully integrated with Python's import system so you don't need to exec anything in globals(). You just:

>>> with httpimport.remote_repo(['package1'], 'http://my-codes.example.com/python_packages'): ...     import package1 ... 

and then package1 is usable for the rest of the script like it was a local resource.


Disclaimer: I'm the author of this module.

like image 182
operatorequals Avatar answered Oct 04 '22 16:10

operatorequals


Yes you can.

Just fetch the module with the url and once you have it store it as a string where you can run it using eval()

Using urllib and eval it can be done easily:

import urllib.request a = urllib.request.urlopen(url) eval(a.read()) 

Do note that some modules (such as Pygame and Pydub) require runtimes and they could not be run using eval() because of the missing runtimes.

Good luck with your project, I hope I helped.

like image 29
Xantium Avatar answered Oct 04 '22 14:10

Xantium