473,666 Members | 2,449 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

if (__name__ == '__main__'): main(sys.argv[1:])

I have a question about proper Python style when it comes to having a main
function in a module. I'm fairly new to Python - a few months of
very-part-time tinkering (lots'o'Java at work, shrug); my apologies if this
has been hashed out before. Random Googling didn't enlighten me, so instead
I'll ask here. :)

Take the following strmod.py (it's silly, I know):
----
import sys
import getopt

def main(sys_argv):
try:
opts, args = getopt.getopt(s ys_argv, "clstu")

for str_toPrint in args:
for opt, arg in opts:
if opt == '-c':
str_toPrint = str_toPrint.cap italize()
elif opt == '-l':
str_toPrint = str_toPrint.low er()
elif opt == '-s':
str_toPrint = str_toPrint.swa pcase()
elif opt == '-t':
str_toPrint = str_toPrint.tit le()
elif opt == '-u':
str_toPrint = str_toPrint.upp er()

print str_toPrint
except getopt.GetoptEr ror:
pass
if (__name__ == '__main__'):
main(sys.argv[1:])
----

Now, from what I have seen in terms of examples etc. would do something like
(note the lack of sys_argv, and how sys.argv[1:] is imbedded in the
getop.getopt call):

----
import sys
import getopt

def main():
try:
opts, args = getopt.getopt(s ys.argv[1:], "clstu")
# ...
print str_toPrint
except getopt.GetoptEr ror:
pass
if (__name__ == '__main__'):
main()
----

This essentially makes strmod.main() uncallable by anything else that needs
command line args, right? The first pattern allows calls like
strmod.main("-t -s pRINT mE tHE sAME uNTESTED".split ()) from elsewhere. It
seems to me that this would be very helpful when writing low-level utilities
that could be driven by other higher-level utilities without needing to fall
back to OS calls, etc.

So... Is this a good idea? Bad idea? Is there a better way? I'm just
trying to not fall into any newbie pit traps ("Hey, what's at the bottom of
this nifty hole?" ;).

TIA,
Eli

--
Give a man some mud, and he plays for a day.
Teach a man to mud, and he plays for a lifetime.
WickedGrey.com uses SpamBayes on incoming email:
http://spambayes.sourceforge.net/
--
Jul 18 '05 #1
1 11442
Eli Stevens (WG.c) wrote:
I have a question about proper Python style when it comes to having a main
function in a module. I'm fairly new to Python - a few months of
very-part-time tinkering (lots'o'Java at work, shrug); my apologies if this
has been hashed out before. Random Googling didn't enlighten me, so instead
I'll ask here. :)

if (__name__ == '__main__'):
main(sys.argv[1:]) vs. if (__name__ == '__main__'):
main()


As I think you suspected, "good style" is best determined in this
case by testability. Go with the former and you aren't likely
to regret it.

-Peter
Jul 18 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
88301
by: Ivan Voras | last post by:
In a code such as: if len(sys.argv) < 2: print "I need arguments!" sys.exit(1) Is sys.exit() really a good choice? Is there something more elegant? (I tried return but it is valid only in a function)
0
1474
by: Dave Harris | last post by:
Something to think about...I'm not sure if this is a problem for anyone. IDLE currently issues a traceback when running a program which contains sys.exit(). For example, the program: if __name__ == "__main__": sys.exit(False) shows the following in the IDLE shell window: Traceback (most recent call last):
9
3598
by: Bengt dePaulis | last post by:
I have a local directory that I want to include in my sys.path How to save it permanently? Regards /Bengt
7
9870
by: Bernd Danberg | last post by:
Hi, I have a real strange problem with the command line arguments given to the main-function and together with using std::string: #include <string> int _tmain(int argc, _TCHAR* argv) { std::string str(argv); println(str.c_str());
21
1520
by: Michael Hoffman | last post by:
What would people think about adding sys to __builtins__ so that "import sys" is no longer necessary? This is something I must add to every script I write that's not a one-liner since they have this idiom at the bottom: if __name__ == "__main__": sys.exit(main(sys.argv)) Additionally, the necessity of "import sys" makes some one-liners a little more unwieldy than they should be--it is surely the module I am
13
2436
by: robinsonreyna | last post by:
Hi everyone Is it possible to write a program which do not have a main() function. The program should compile and run. Please give sample code to do this.
3
2346
by: Fuzzyman | last post by:
Hello all, I am messing with namespaces, so that code I exec thinks it is executing in the __main__ module. I have the following code : import imp import sys
2
2078
by: Bob Nelson | last post by:
Concerning program startup in a hosted environment, both C90 and C99 require that the implementation provide main's ``argv'' strings in lowercase if the host environment is not capable of supply both uppercase and lowercase letters. While I hesitate to mention any specific platform in this query -- presuming such an implementation capable of only uppercase letters, what is the reason for the C language's ensuring that the strings, if...
2
2428
by: Ben Bacarisse | last post by:
candide <candide@free.invalidwrites: argv can't be an array. It is a function parameter and arrays can't be passed to functions in C. There is indeed an array "out there" but all main can ever see is a pointer to it. Not everyone likes the term "array of strings" -- it can be see as a bit woolly. What is not in question (I hope) is that, inside main, argv is not an array: it is a pointer to the first element of an array
0
8440
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8352
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8863
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8549
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8636
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7378
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5661
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4358
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1763
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.