• Home
  • Blog
  • Learning Python: module import issues

Learning Python: module import issues

Vincent Danen

March 08, 2009

So I've taken it upon myself to learn Python, which is something I've wanted to do for a while. I usually write code in PHP or shellscript, with the odd thing in Perl every once in a while (but I'm not a real big fan of perl and I don't have the desire to dig into it more). A lot of my more sophisticated projects that can't be done in shellscript are usually done with CLI PHP. But Python is something I've wanted to learn, so I've started digging into it and my first dive is rewriting a CLI PHP program "suite" that creates and scours a database for RPM information (dependencies, requires, files, etc.).

I've been at it for about 2 weeks now with what little time I have and the original suite consists of two programs: rqp and rqs. These two programs were a result of a rewrite of the "srpm" PHP program that Stew Benedict wrote years ago for the Mandriva secteam (and which has proven invaluable of the years). It handled only src.rpm files, so I rewrote and extended it to handle binary and source rpm files (rqp and rqs respectively). It was a quick-n-dirty extension that was used for a few years on the Mandriva secteam and worked really well (and probably is still working well for them).

I've gotten rqp converted to Python and it's working quite well. Because rqp and rqs share a lot of functions, I wanted to write rqp.py and rqs.py and have a shared module between them (rq.py) and this is where I'm having issues. Does anyone know how to have a module get access to an object from the calling program? For instance, rqp uses the optparse module to nicely handle the commandline arguments, but a lot of the modules use options.foo to look up arguments that were passed. The functions in rq.py (the module) can't seem to get the value of options, and while I could put the optparse stuff in the module, it would leave the actual rqp and rqs programs really really small (and I'd have to either put in two functions because the two programs use different syntax). So I've got in rqp.py:

import rq

which works ok, but if rq.db_connect() requires options.database (for instance), it can't get it. So in rq.py, I tried doing a circular import or whatever it's called by doing:

import options from rqp

But this doesn't want to work either. The output looks quite sad:

% ./rqp.py -d
rqp 0.2 ($Id: rqp 275 2009-03-07 22:34:15Z vdanen $)

Traceback (most recent call last):
  File "./rqp.py", line 548, in 
    import rq
  File "/Users/vdanen/svn/scripts/rq/trunk/rq.py", line 11, in 
    from rqp import options
ImportError: cannot import name options

There has to be a way to make the options variable (and one or two others I think) accessible to the module, but I haven't been able to find a way to do it. Does anyone know how this can be accomplished?

Leave a Comment

Comments use MarkDown. Need help? MarkDown Cheatsheet