I am beginning python and working on a project, and one th开发者_运维技巧ing 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 connect to a server, download a python script on demand, and run that script that was just downloaded without having to restart the program or hard code that specific script in to the program.
The program I'm working with uses Python for scripting and execution, and C++ for the other code such as rendering and math.
I would like to be able to use python to run scripts that have been downloaded from a server (for things such as user generated content).
I was wondering if that was possible, or if I should use another scripting language (possibly LUA) for that situation?
Thanks, Th3flyboy
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.
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.
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
- https://stackoverflow.com/questions/tagged/urllib2
- https://stackoverflow.com/questions/tagged/subprocess
精彩评论