Executing .pyc using python c api

88888 Dihedral dihedral88888 at googlemail.com
Tue Nov 29 09:19:55 EST 2011


On Tuesday, November 29, 2011 5:02:31 PM UTC+8, Ulrich Eckhardt wrote:
> Am 29.11.2011 08:34, schrieb Mrinalini Kulkarni:
> > I need to run .pyc files using python c api. if i do PyImport_Import it
> > executes the script. However, i need to pass a set of variables and
> > their values which will be accessed from within the script. How can this
> > be done.
> 
> I don't think what you want is possible, due to a think-o in your 
> design. Let me explain...
> Firstly, .pyc files are basically the same as .py files, only in a 
> different presentation. Then, PyImport_Import is basically the same as 
> using "import" in a Python program. Now, and that is where your fault 
> lies, importing a module actually means executing that module! For 
> example, the definition of a function is code that when executed will 
> cause a function to be created and attached to the current scope with 
> the according name. This is what makes it so easy to implement local 
> functions that are parametrized by arguments to the outer function. 
> Still, a function is not something that is "static", like in C or Java, 
> but rather the result of executing its function definition.
> 
> Now, how to get around this? The specialty about the import is that the 
> __name__ attribute is not set to "__main__", upon which many scripts 
> already react. So, in order to "prevent execution" (in the sense that 
> you probably mean), you simply wrap the according code in a function. 
> The function definition will then be executed, giving you a function 
> that you can call with the according parameters, but the function itself 
> will not be executed automatically. If you want that to happen when 
> executing the .pyc file directly, check the content of __name__ and call 
> the function if it is "__main__".
> 
> Note that another approach would be introspection, traversing through 
> the namespaces to find out those parameters, but I would consider this 
> solution as hackish if the one above is feasible.
> 
> Good luck!
> 
> Uli

Please use psyco and pyrex and C or whatever that can read saved results in a file, or just learn how to replace a hash or a sort in  python's build in library of better speed, don't do reference overheads in 
those c type variables that won't overflow and underflow  and used by other objects in python. Not trivial but well documented to cheer for a race!

 



More information about the Python-list mailing list