Run pyc file without specifying python path ?

Dave Angel davea at ieee.org
Sun Aug 2 05:35:34 EDT 2009


Barak, Ron wrote:
> Hi Dave,
>
> It seems like I don't understand your solution.
> I use the (appatched) soapAPI.py as the wrapper to parsing.pyc.
> However, if I do (for instance):
>
> $ python -u parsing.pyc -U aaa
>
> The last line of the output is (as expected):
>
> return_code: 12 ; params: {'username': 'aaa'}
>
> But, if I try the following:
>
> $ soapAPI.py -U aaa
>
> I don't get this line. Only the output to stderr gets printed to the screen.
>
> Bye,
> Ron.
>
>   
Hi Ron,

To make it easier for anybody following this thread, let me post the 
minimum equivalent source files, inline.

parsing.py:
------------------------------
#!/usr/bin/env python

import sys

def main():
    print >> sys.stderr, "This is stderr output"
    return  5, sys.argv

if __name__ == "__main__":
    return_code, params = main()
    print "return_code:",return_code,"; params:",params
    sys.exit(return_code)
-------------------------------
soapapi.py:
-------------------------------
#!/usr/bin/env python

import sys
import parsing

parsing.main()
------------------------------


When I run soapapi.;py, it indeed prints only the stderr output.

The solution is to move (most or all) of the top-level code of 
parsing.py into a main() function.  Since you already have a main(), 
I'll rename that, and make a new one that calls it.

new   parsing.py:
-------------------------------
#!/usr/bin/env python

import sys

def innermain():
    print >> sys.stderr, "This is stderr output"
    return  5, sys.argv

def main():
    return_code, params = innermain()
    print "return_code:",return_code,"; params:",params
    sys.exit(return_code)

if __name__ == "__main__":
    main()
-------------------------------

The output is now two lines, one from innermain(), and one from main().  
And it's the same whether the user runs  parsing.py  or   soapAPI.py

To clarify what happened, realize that when the user invokes  
parsing.py, the module is considered a script, and gets a pseudo-name of 
"__main__"    When that same module is imported by another one, it is 
considered a library module, and gets its own name "parsing"

So any logic that explicitly checks for "__main__" has to change,  
because we want identical behavior in the two cases.

DaveA




More information about the Python-list mailing list