Skip to content Skip to sidebar Skip to footer

Add A Python Script At Runtime

I am beginning python and working on a project, and one thing I would like to be able to do is download and run a script dynamically at runtime. The general idea is to be able to

Solution 1:

You can definitely do this. Use urllib to download or generate the script, then import it. It'll work like a charm every time, as long as you download the script to your PYTHONPATH.

For example:

from urllib import urlretrieve
urlretrieve('http://www.mysite.com/myscript.py', '/home/me/script.py')
import script

You can also generate the script yourself from a template, pulling data from online (perhaps in xml or from a database) and using Python's text processing capabilities to make the necessary adjustments.


Solution 2:

This is quite possible, though hugely insecure.

You need to download using urllib2.urlopen and then executing the result using exec. I am reluctant to explain further because of the security implications.

Edit: An explanation about the security issues.

In Python (CPython) currently there is no way to have a sandbox. The result is any untrusted code has access to all the capabilities Python has on your machine (for the specific user). This can be partially solved by using a specialised user, and better operating system level solutions. They are complicated, however.

An example of sandboxing is the way Java restrict applets from having total access to the machine.

Lua is frequently used in games programming. The famous example is World of Warcraft. One of the main reasons is that it can be sandboxed. Deciding the capabilities to allow the untrusted code is not simple, but at least it can be secured much easier than Python.


Solution 3:

Any programming language that allows to run an external script should be able to do your job. That practically means all languages. Almost all dynamic languages will do.

With python, there are multitude of ways to connect to a server and fetch the url. For execution, you could use subprocess module


Post a Comment for "Add A Python Script At Runtime"