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()
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
andeval
it can be done easily: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.