On 24 January 2013 16:08, Oscar Benjamin <oscar.j.benja...@gmail.com> wrote: > On 24 January 2013 15:51, Tim Golden <m...@timgolden.me.uk> wrote: >> On 24/01/2013 15:28, Oscar Benjamin wrote: >>> On 24 January 2013 13:45, Tim Golden <m...@timgolden.me.uk> wrote: >>>> On 24/01/2013 11:30, Oscar Benjamin wrote: >>>>> I don't really understand what your spec is. Why do you need to >>>>> inspect this information from sys.argv? Can you not just always use >>>>> 'python -m pkg' as your entry point? >>>> >>> [SNIP] >>>> >>>> For completeness, I'm talking about the cherrypy Autoreloader which >>>> attempts to restart (via execv) whatever process was responsible for >>>> loading it in the first place, via an identical or equivalent command >>>> line. The current (cherrypy) code simply joins sys.executable and >>>> sys.argv but this fails in the face of python -m as we have seen. >>>> >>>> The cherrypy package has no especial knowledge of the structure of the >>>> application which imported it and so must piece together the command >>>> line somehow. Clearly, I can take various approaches of the sort >>>> which you've outlined, or subclass the reloader, or fetch the original >>>> command line from the OS, etc. It's not that this is a showstopper, >>>> merely slightly surprising. (To me). >>> >>> Ok I understand. Then I guess you want: >>> >>> import __main__ >>> pkg = __main__.__package__ >> >> Brilliant. Never thought of importing __main__. Thanks. >> >> For the benefit of anyone still watching, the code (which has to be >> compatible back to 2.3) looks something like this: >> >> <code> >> import __main__ >> >> # [.. .snip ...] >> >> try: >> is_package = bool(__main__.__package__) >> except NameError: >> is_package = False >> if is_package: >> args = [sys.executable, '-m', __main__.__package__] + sys.argv[1:] >> else: >> args = [sys.executable] + sys.argv >> >> os.chdir(_startup_cwd) # avoids relative/absolute issues >> os.execv(args[0], args) >> >> </code> >> >> I don't pretend it's foolproot, but it certainly works for my particular >> case. Nor have I considered it against all the cases identified in PEP >> 432: http://www.python.org/dev/peps/pep-0432/#configuring-sys-argv > > Does it work if you use the -m option to run a module rather than a script?
Sorry that was written incorrectly. I meant to say: does it work when a module is directly on sys.path rather than as a submodule of a package? In this case __package__ is set to the empty string if run with -m or None if run with a direct path. So the check needs to be "__package__ is not None" rather than "bool(__package__)". Oscar -- http://mail.python.org/mailman/listinfo/python-list