473,797 Members | 3,015 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Loading and executing an arbitrary Python script from within Python

I'm writing a game in C++ that calls out to Python for scripting. The C++
kernel holds an instance of ScriptCtl and calls the load(filename) method to
load a script, then run() to run all loaded scripts.

<code>
[scriptctl.py]
class ScriptCtl:
threads=[]

def load(self, filename):
f=file(filename , 'r')
contents=f.read ()
f.close()
exec(contents) #contents exec'ed within the current scope and
namespace, not within their own
self.threads.ap pend(main)

def run(self):
while self.threads:
for g in self.threads:
try:
g.next()
except StopIteration:
self.threads.re move(g)

[cutscene.py]
from __future__ import generators
def cutscene():
from time import time
import sys
from utility import sleep

print "EVIL KNIGHT: I will kill you now!"; sys.stdout.flus h()
for s in sleep(1): yield None
print "OUR HERO: I shall fight you to the death. Bring it on!";
sys.stdout.flus h()
for s in sleep(1.5): yield None
print "***End of cutscene***"; sys.stdout.flus h()

main=cutscene() #initialize the generator for use by scriptctl
</code>

This works, barely. As a result of using exec, each script is executed in
ScriptCtl.load( )'s namespace. Because of this, imports have to be done inside
the script functions, or the imports go out of scope before the functions get
called (in scriptctl.run() ). Imports also have to be done as from
scriptctl.py, even though scriptctl.py deeper in the package hierarchy (so
instead of 'import core.utility' I must do 'import utility' because both
utility.py and scriptctl.py are in the same folder (core).

This sucks.

How else can I solve this problem? Ideally, I'd use Stackless Python
microthreads, but version 3.0 is not out yet and there is no documentation on
the current was to do microthreads.

Any ideas? I'm stuck.
Thanks, Dustin
Jul 18 '05 #1
2 2114
Quoth Raymond Arthur St. Marie II of III :
[...]
Did I get the concept wrong about using
a generater in a try section? Is this code legal anyone?

Or does this only pertain to the yeild statement in a try.


The prohibition is on yield statements in the try section of a
try-finally statement. The posted code is fine.

(This is prohibited because there is no guarantee that execution
will ever return to the generator after the yield -- the caller
might never call .next() again -- and so the finally block might
never be executed. This was judged too grave a violation of
try/finally's semantics to permit.)

--
Steven Taschuk st******@telusp lanet.net
"Its force is immeasurable. Even Computer cannot determine it."
-- _Space: 1999_ episode "Black Sun"

Jul 18 '05 #2
TheDustbustr wrote:

.....
This sucks.
Indeed.
How else can I solve this problem? Ideally, I'd use Stackless Python
microthreads, but version 3.0 is not out yet and there is no documentation on
the current way to do microthreads.


Stackless is in fact the best way to do this, IMHO.

Unfortunately, 5 minutes before getting SLP 3.0 out,
most support for Stackless was shut down (no names here).
So I have to find a way to continue, which I definately
will, but things will slow down, again.

Maybe you can help me, and I will help you!

cheers - chris

--
Christian Tismer :^) <mailto:ti****@ tismer.com>
Mission Impossible 5oftware : Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/
14109 Berlin : PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776
PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04
whom do you want to sponsor today? http://www.stackless.com/

Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1843
by: SS | last post by:
I am trying to execute some python commands within a perl script and running into problems. The following works: python -c "import mypkg;do this; do that" however when I try to do something like #!/bin/perl -w ...... ...... $cmd = "import mypkg; do this; do that"; $string = `python -c \"$cmd\"`;
1
2146
by: cwnewbe1 | last post by:
I would like to be able to add environment symbols to the Microsoft XP registry. I tried the example in the Python Cookbook by Orielly by running the script locally and it worked fine. Although I noticed that even though the symbol showed immediatedly in the registry by viewing with regedit but not via a new dos command console, thus, I am forced to reboot to make it 'lock in'. Is this normal? My wish is to have the script invoked in...
1
1917
by: David Faden | last post by:
Hi, Given arbitrary Python source code input by the user, I want to get the result of executing that source as an expression if it is an expression and otherwise execute the source as a statement. Currently, I'm accomplishing this as follows (in a category on NSString), but it seems kludgy to rely on detecting a syntax error. - (PyObject*)executePythonSourceWithGlobals:(PyObject*)globals {
0
1967
by: Nick Coghlan | last post by:
Anyone playing with the CPython interpreter's new command line switch might have noticed that it only works with top-level modules (i.e. scripts that are directly on sys.path). If the script is inside a package, the invocation will fail with a "Module not found" error. This PEP is aimed at fixing that :) Cheers, Nick.
15
2610
by: Nick Coghlan | last post by:
Python 2.4's -m command line switch only works for modules directly on sys.path. Trying to use it with modules inside packages will fail with a "Module not found" error. This PEP aims to fix that for Python 2.5. Previously, posting of a draft version of the PEP to python-dev and python-list didn't actually generate any responses. I'm not sure if that's an indication that people don't see the restriction to top-level modules as a problem...
11
1979
by: Bryant Huang | last post by:
Hello! I would like to read in files, during run-time, which contain plain Python function definitions, and then call those functions by their string name. In other words, I'd like to read in arbitrary files with function definitions, using a typical 'open()' call, but then have those functions available for use. The 'import' keyword is not appropriate, AFAIK, because I want to be able to open any file, not one that I know ahead of...
10
4887
by: sneill | last post by:
Using XMLHTTP and DOM I'm able to load new HTML page content. I'd now like to load small snippets of javascript with the HTML markup and have that <script> incorporated into the page. If any of the loaded script exists outside a function definition (eg: a call to a function), I'd like that code to be executed as soon as its added to the DOM. Can anyone suggest the best way to do this? I've Googled but not found anything comprehensive....
3
3565
by: olaufr | last post by:
Hi, I need to call a python script, with command line arguments (it is an autonomous script with a __main__), from within another python script. Can I use exec() or execfile() for this? How to pass the arguments? Thanks, Olivier.
5
1650
by: tdan | last post by:
When loading Javascript files with <scripttags in your HTML, do the files load AND run sequentially or does the HTML simply load the files and run them simultaneously. If not, how can you force them to run sequentially?
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9536
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10245
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10021
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9063
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7559
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5458
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3748
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2933
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.