Dynamic HTML from Python Script

I have a python script whose output i want to dynamically display on a webpage which will be hosted using Apache. How do I do that

Posted On: Sunday 11th of November 2012 09:24:18 PM Total Views:  315
View Complete with Replies

Related Messages:

dynamically generated runtime methods & reflection   (99 Views)
Hi all, First, apologies if anyone gets this twice, but it took me quite a while to figure out that is evidently rejecting all mail from my mail server because I don't have reverse DNS configured. Anyway: I'm not even sure how to phrase this question properly or the right terminology on this so bear with me. What I'm looking to find out is a) is there a functionality in Python where I can call a method I have not defined ahead of time, and based on the method name, change the functionality of the method at runtime b) if not, what is the "Pythonic" approach to the problem outlined below Any recommendations on how to approach the problem differently are welcome. I've googled and read my Python reference pretty extensively and I've found some hints but nothing that really answered my questions, so here I am :-) I did figure out that you can overload __getattr__ in a clas to define a new method at runtime, but I got stuck when I couldn't figure out how to have a method know what name it was originally called with. That's the basic question, see below for the context I'm asking the question in and *why* I want to do the above :-) ----- The software product I work on has a socket-based API that can be accessed directly via telnet & manually typing commands, or by a set of Perl modules that wrap the socket functionality. I am looking to write a set of Python modules that match the same functionality. Basically you can telnet to a port and type something like item.list "param1=value1", "param2=value2" And it will return the results (if any) to you in a given format along with a response code, e.g. 200 OK or 400 ERROR. The Perl modules just wrap this so that instead of the above, you can do something like this: $MySocketServer = new SocketServer(Host=>'127.0.0.'1, Port=>'9999'); if (! $MySocketServer->ListItem(itemName=>$item_name)) { print "failed to retrieve list"; print "reason: " . $MySocketServer->GetErrorMsg(); exit; } The ListItem() method handles the work of communicating across the socket, waiting for the response, and determine the success/failure based on the return code. The part where it gets interesting is that our Perl modules don't actually have a ListItem() method. Instead, there is a generalized "_api_func()" method that looks at the name of the method you called (using Autoload I believe, for any Perlheads out there), and bases the action taken on the name. In the example above, for instance, it sees that you called ListItem(), so it transforms that to item.list and makes the parameters of the method the parameters that are passed to item.list via the socket server. Then it takes the response back from the socket to determine the function return code. If there are any results such as a list of items, they are then able to be accessed through a reference to a hash of the results, and there is a GetResultRef accessor function. In essence, our Perl modules are an incredibly lightweight, simplistic wrapper for the socket-based API, and almost all of the work is offloaded to the API implementation server-side. I welcome any suggestions, feedback, sample code, documentation, whitepapers etc. The only thing I don't want to have to do is go and define a separate method for every single one of the possible permutations of socket commands if I can avoid it! -----
adding properties dynamically (how to?)   (113 Views)
Andr a crit : > I didn't want to hijack the original thread but I have basically the > same request... > > On Aug 17, 7:09 am, Bruno Desthuilliers > wrote: >> akonsu a crit :> hello, >> > [SNIP] > >> Wrong solution to your problem, I'd say. Let's start again: >> >> """ >> > i need to add properties to instances dynamically during run time. >> > this is because their names are determined by the database contents. >> """ >> >> Care to elaborate I may be wrong, but I suspect you're trying to roll >> your own python/database mapper. If so, there are quite a couple Python >> ORMs around. Else, please tell us more. > > I'm not the original poster, but I'd like to do the same thing (for a > different reason). > > I have a program (crunchy) that is extensible via plugins. New > options available via plugins can be turned on or off (or selected > among a list of options). I have a module for user preferences (let's > call it that allows the setting of these options (and do > error checking, automatic saving of the options selected for future > sessions, etc.). These options are implemented as properties. > > Currently I have it simplified so that only two lines need to be added > to to add new options; something like > options = { ... > 'new_option': [value1, value2, ..., valueN], > ...} > > and > class Preferences(object): > ... > > new_option = make_property('new_option', 'some nicely worded help > string') > > === > make_property is a custom define function that return fgets, fsets, > fdel and doc. You may want to write your own descriptor object instead. The 'property' class is just one possible way to use the descriptor protocol for "smart" attributes. > Ideally, I'd like to be able to define new would-be properties from > the plugin and add them to the class prior to creating instances. In > other words, have something like > > === > for option in options_defined_in_plugins: > add_option_as_property_to_Preferences(Preferences, option, ...) > > user_preferences = Preferences() Not the same problem as the OP here. Your properties are not per-instance, so just adding them to the class is ok. Remember that in Python, classes are objects too, and (a couple corner cases set aside) nothing prevent you from dynamically adding attributes to an object. The following snippets are equivalent: class Foo1(object): attrib = object() class Foo2(object): pass Foo2.attrib = object() class Foo3(object): pass setattr(Foo3, 'attrib', object())
Re: add method to class dynamically?   (108 Views)
En Wed, 22 Oct 2008 10:37:11 -0200, Jean-Paul Calderone escribi: > On Wed, 22 Oct 2008 08:29:08 -0400, Neal Becker > wrote: >> I have a class (actually implemented in c++ using boost:ython). For >> an instance of this class, 'r', I'd like to support len (r). I don't >> want to add it to the c++ code, because this is a unique situation: >> this class should not normally support len(). >> >> So I try: >> r = ring_int (10) >> r.__len__ = lambda: 10 >> >> This doesn't work: >>>>> len(r) >> TypeError: object of type 'ring_int' has no len() > Special methods aren't looked up in the instance dict of instances of > new-style classes. Exactly what constitutes the set of "special methods" > is a bit undefined. Consider anything that CPython has to look up to > satisfy some other operation, such as len or +, to be a special method > and don't rely on _either_ it being looked up on the instance or it _not_ > being looked up on the instance (ie, don't put a method there and expect > it > not to be called). The methods which are actually considered special by > CPython can change and has in the past. special methods have names like "__special__" (except "next" -used in the iterator protocol- which will become __next__ in 3.0; any others) - this is stated here (But I'm sure you already knew that) To the OP: you may use a "template method". In the C++ class do the equivalent of: class Ring_int(int): def __len__(self): return self._len_impl() def _len_impl(self): raise NotImplementedError Now you can override _len_impl in the instance: py> r = Ring_int(10) py> r._len_impl = lambda: 10 py> len(r) 10 Note that hasattr(r, '__len__') is true, don't use that check in this case. -- Gabriel Genellina
Ctypes module - looking for a way to dynamically call exportedfunction from a set of dlls   (104 Views)
I'm using the ctypes module to load my dlls. I have some 10 dlls the names of those are passed to a fucntion which then loads the passed dll. Now every dll has a getversion function. eg: A.dll, B.dll, C.dll are the dlls and GetVersion functions are as: A_getVersion(), B_getVersion(), C_getVesion() The functionality I'm lookking for is that depending on the dll passed the right getVersion should be passed. I'm able to load the all the dlls passed to the function but I'm not able to call the function names dynamically Please help
dynamic attribute syntax   (79 Views)
On 17 Aug, 21:29, castironpi wrote: > > What are the changes, pros and cons, involved in something like: > > obj:att for a dynamic access, and obj.att for static A previous proposal and discussion can be found here: Paul , On Aug 17, 3:05pm, Fredrik Lundh wrote: > castironpi wrote: > > 'obj.prop' has an easy access, but > > > att= 'prop' > > getattr( obj, att ) > > > is much clumsier, while no less useful, maybe more. > > maybe more ok, you *are* utterly and completely unable to post > anything that makes any sense at all to anyone that uses Python. > plonkeliplonk. More constructive contributions on both sides there. Good one.
Re: dynamically creating html code with python...   (168 Views)
btw, credits for the code shown below also for: wrote : > This makes sense.
Re: dynamically creating html code with python...   (185 Views)
On Mon, Aug 11, 2008 at 10:05 AM, wrote: > > >
Re: dynamically creating html code with python...   (116 Views)
On Mon, Aug 11, 2008 at 9:15 AM, wrote: > Code: > f=StringIO.StringIO() > f.write('data ****ysis') > f.write(urllib.urlopen("http://localhost/path2Libs/", urllib.urlencode(TheData))) > f.write("") > > print "Content-type: text/html\n" > print > f.close() > > > What is wrong with this approach/code Is there an easier way of doing it A StringIO object works a lot like a file. When you write to it, it keeps track of the current position in the file. When you read from it, it reads from the current position to the end of the file. Once you're done writing to the StringIO object, you can rewind the position to the beggining and then read to the end, like this: f = StringIO.StringIO() f.write('This is some data') print StringIO objects also have a special getvalue() method, which allows you to get the entire contents without changing the current position. You can replace your with f.getvalue() without having to mess with seek(), but then your code won't work with real files, if that's important. -- Jerry
Re: dynamically load from module import xxx   (107 Views)
Guilherme Polo wrote: > On Tue, Jul 1, 2008 at 12:11 PM, Neal Becker wrote: >> What is a good way to emulate: >> >> from module import xxx >> where 'module' is a dynamically generated string >> >> __import__ ('modulename', fromlist=['xxx']) >> >> seems to be what I want, but then it seems 'xxx' is not placed in >> globals() (which makes me wonder, what exactly did fromlist do) > > fromlist is used for importing subpackages/submodules of the first arg > of __import__. Since you are using "modulename", I'm guessing it is > not a package, fromlist will do nothing for you. > To solve your problem you could do getattr(__import__('modulename'), > 'xxx'). This seems to be what I want, don't know if there is a simpler way: stuff =['A','B'] module = __import__ (modulename) for e in stuff: globals().update({e : module.__dict__[e]})
python: lexical or dynamic scope?   (86 Views)
i cant figure outif python has lexical or general scope. it seems functions have lexical scope but with some restrictions and some non-function scopes are dynamic
Creating dynamic objects with dynamic constructor args   (91 Views)
I'd like to create objects on the fly from a pointer to the class using: instance = klass() But I need to be able to pass in variables to the __init__ method. I can recover the arguments using the inspect.argspec, but how do I call __init__ with a list of arguments and have them unpacked to the argument list rather than passed as a single object ie. class T: def __init__(self, foo, bar): = foo = bar argspec = inspect.argspec(T.__init__) args = (1, 2) how do you call T(args)
Re: dynamically created names / simple problem   (132 Views)
Robert Bossy wrote: > Jules Stevenson wrote: > >> all, >> >> I'm fairly green to python and programming, so please go gently. The >> following code >> >> for display in secondary: >> >> self.("so_active_"+display) = wx.CheckBox(self.so_panel, -1, "checkbox_2") >> >> Errors, because of the apparent nastyness at the beginning. What Im >> trying to do is loop through a list and create uniquely named wx >> widgets based on the list values. Obviously the above doesnt work, >> and is probably naughty whats a good approach for achieving this >> >> > > > What you're looking for is the builtin function setattr: > > > Your snippet would be written (not tested): > > for display in secondary: > > setattr(self, "so_active_"+display, wx.CheckBox(self.so_panel, -1, > "checkbox_2")) Damn! The indentation didn't came out right, it should be: for display in secondary: setattr(self, "so_active_"+display, wx.CheckBox(self.so_panel, -1,"checkbox_2")) RB
get the size of a dynamically changing file fast ?   (130 Views)
hello, I've a program (not written in Python) that generates a few thousands bytes per second, these files are dumped in 2 buffers (files), at in interval time of 50 msec, the files can be read by another program, to do further processing. A program written in VB or delphi can handle the data in the 2 buffers perfectly. Sometimes Python is also able to process the data correctly, but often it can't :-( I keep one of the files open en test the size of the open datafile each 50 msec. I have tried os.stat ( ....) [ ST_SIZE] os.path.getsize ( ... ) but they both have the same behaviour, sometimes it works, and the data is collected each 50 .. 100 msec, sometimes 1 .. 1.5 seconds is needed to detect a change in filesize. I'm using python 2.4 on winXP. Is there a solution for this problem
dynamic type variable   (67 Views)
Python's variable is dynamic type,is it But why this can't work >>> 3 + 'a' Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'str' So I see the number 3 can't be converted to string type automacially.
Using python for dynamic behavior from C++   (80 Views)
Hi all, I am looking into using Python to introduce dynamic behavior in my C++, e.g. something like a simulation where objects can interact with eachother. I know Python can be called from C++, but is it possible to call a binary compiled Python file / array from C++ The reason I ask is that if my objects call a script every tick to do something, I would not like to let the python interpreter recompile the same code over and over again. Any pointers to how I can do that
How to code dynamically created methods?   (101 Views)
I've tried a bazillion ways to code dynamically generated methods, to no avail. The following snippet is a very simplified (and artificial) demo of the problem I'm running into, featuring my latest attempt at this. The idea here is to use __getattr__ to trap any attempt to invoke a nonexistent method, have it return a generic handler called _auto which creates the new method dynamically, invokes it, and "installs" it in the class, so that subsequent calls to the same method go directly to the newly created method, instead of to __getattr__. It is this last step, the "installation" of the new method, that is giving me problems. class A( object ): def __getattr__( self, name ): self._auto_name = name return self._auto def hello( self, name ): print "hi! my name is %s" % name def _auto( self, *args ): name = self._auto_name def m( self, *args ): self.hello( name ) m( self, *args ) m = classmethod( m ) setattr( A, name, m ) x = A() # ok # bombs >>> reload(test) hi! my name is foo Traceback (most recent call last): File "", line 1, in File "", line 19, in File "", line 12, in m self.hello( name ) TypeError: unbound method hello() must be called with A instance as first argument (got str instance instead) >>> I'm sure that the problem is with my naive attempt to add a method to class A dynamically (in the last two lines of the definition of _auto). What's the right way to do this
Pythomnic 2.0,framework for building reliable highly dynamic network services   (100 Views)
Major new features in version 2.0: * Support for distributed transactions * Network-wide service health monitoring * Dynamic service discovery at runtime * Support for module level persistency * Full support for JMS integration The what's new page: Pythomnic is a Python framework for distributed service networks. It focuses on the following main principles: * Network services are relied upon and volatile at the same time. This dilemma has to be addressed. Pythomnic supports transparent code and configuration changes that do not require service restart. * Building reliable network services is an integration task more than anything else. Pythomnic offers facilities to build distributed services spanning multiple machines. * Nothing is fail-safe, the service must be fault-tolerant to survive. Pythomnic offers the developers various fault-tolerance techniques. Project site:
python extension dynamic linking   (89 Views)
I am writing Python extension in C++, in this extension I am using methods from another Python extension. On Linux I am currently linking my extension with used Python extension -- what is quite ugly. gcc ... -lgdi where ...
Re: Ctypes module - looking for a way to dynamically call exportedfunction from a set of dlls   (123 Views)
En Tue, 26 Aug 2008 07:42:50 -0300, escribi: > > > I'm using the ctypes module to load my dlls. > > I have some 10 dlls the names of those are passed to a fucntion which > ...
dynamically getting loggers   (83 Views)
is there a way to dynamically get all the active loggers i currently have code like this in different areas of the program: import logging log = logging.getLogger('foo') i would like to write a function that dynamically get a list ...