Executing .pyc using python c api
Ulrich Eckhardt
ulrich.eckhardt at dominolaser.com
Tue Nov 29 04:02:31 EST 2011
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
More information about the Python-list
mailing list