The Artima Developer Community
Sponsored Link

Weblogs Forum
Python main() functions

31 replies on 3 pages. Most recent reply: Aug 30, 2016 10:52 AM by Michael Stueben

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 31 replies on 3 pages [ « | 1 2 3 ]
lucian c

Posts: 1
Nickname: lucianc
Registered: Feb, 2015

Re: Python main() functions Posted: Feb 11, 2015 3:39 AM
Reply to this message Reply
Advertisement
this fragment:
def main(argv=None):
if argv is None:
argv = sys.argv
opt, args = parser.parse_args(argv[1:])

if __name__ == "__main__":
sys.exit(main())
when called from the OS shell

c:\Temp>c:\Python27\python test.py arg1 arg2
{}
['arg1', 'arg2']

and from the python's prompt will yield different results:

c:\Temp>c:\Python27\python
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> test.main(['arg1', 'arg2'])
{}
['arg2']
>>> test.main(['arg_that_nobody_cares_of', 'arg1', 'arg2'])
{}
['arg1', 'arg2']

My proposal is the following:
------------------------------------------------------
def main(opts_args=[]):                   # (1)
opt, args = parser.parse_args(opts_args) # (2)

if __name__ == "__main__":
sys.exit(main(sys.argv[1:])) # (3)

------------------------------------------------------
(1) opts_args defaults to [], because calling parser.parse_args(None) will actually parse sys.argv[1:], and you don't want this if calling main() from another script.
(2) if you want to use the script name in the help message, __file__ should do
(3) no more sys.argv parsing past this point

Michael Stueben

Posts: 4
Nickname: csteacher
Registered: Nov, 2015

Re: Python main() functions Posted: Aug 30, 2016 10:52 AM
Reply to this message Reply
This is my fallback shell:

#######################<START OF PROGRAM>#####################
def main():
pass
#------------------------------------------------------------
if __name__ == '__main__':
from time import clock; START_TIME = clock(); main();
print('- '*12);
print('RUN TIME:%6.2f'%(clock()-START_TIME), 'seconds.');
########################<END OF PROGRAM>######################
Output:
- - - - - - - - - - - -
RUN TIME: 0.01 seconds.

I think EVERY program should print the time it takes to run.

Flat View: This topic has 31 replies on 3 pages [ « | 1  2  3 ]
Topic: Simplicity Before Generality, Use Before Reuse Previous Topic   Next Topic Topic: M2Crypto woes


Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2017 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us