[Tutor] identifying the calling module/function

tetsuo2k6 at web.de tetsuo2k6 at web.de
Mon Mar 10 12:43:54 CET 2008


Kent Johnson schrieb:
> tetsuo2k6 at web.de wrote:
> 
>> in dgf.py: (hope the formatting gets good for you, t-bird breaks the 
>> lines badly on my machine...)
>>
>> def csvwriter(*column_definitions):
>>          """Edit Me!"""
>>          if sys.argv[0] == /usr/local/bin/xyz.py:
>>         output_csv_filename = "xyz.csv"
>>     else:
>>         output_csv_filename = raw_input("Name of the file to produce? 
>> (ATTENTION: WILL BE OVERWRITTEN!) ")
> 
> If you can change xyz.py you can avoid this by adding an optional 
> filename parameter to the function.
> 
>>          first_row = ";".join(*column_definitions)
>>          try:
>>                  file = open(output_csv_filename, "w")
>>                  file.write(first_row)
>>                  file.close()
>>          except:
>>                  print("Couldn't open %s for writing." % 
> output_csv_filename)
> 
> It's not such a good idea to hide the exception like this; you might at 
> least want to print the actual exception. Or just let it propagate.
> 
>>                  sys.exit(1)
> 
> You can use the csv module to write the header row, too.
> 
> I would write this as
> 
> def csvwriter(*column_definitions, filename=None):
>     if filename is none:
>         filename = raw_input("Name of the file to produce?
> (ATTENTION: WILL BE OVERWRITTEN!) ")
> 
>     try:
>             out = csv.writer(open(filename, "ab"),
> delimiter=";", quoting=csv.QUOTE_NONE)
>         out.writerow(column_definitions)
>     except Exception, e
>         print("Couldn't open %s for writing." %
> output_csv_filename)
>         print e
>     return out
> 
> Kent
> 

Yeah, I think I get it, thanks!
Paul


More information about the Tutor mailing list