[Tutor] proxy switcher - was Re: I love python / you guys :)

Dave Angel davea at ieee.org
Mon Nov 16 19:30:19 CET 2009


Luke Paireepinart wrote:
>> Here's what I knocked up over lunch.  It doesn't cover the moving of
>> the file, I don't like that it's deep-nested, and I've not tested it,
>> but I welcome criticism and feedback:
>>
>> files = ['file1', 'file2', 'file3', 'file4']
>> settings = ['export http_proxy=', 'ftp_proxy=']
>>
>> for file in files:
>>  with open(file, 'rw') as file:
>>
>>     
>
> Does this actually work?
> I didn't think you could open files as reading and writing?
>
>   
Yes, you can, but not this way.  I'm guessing the op was changing his 
mind back and forth, between having two files, one for reading and one 
for writing, and trying to do it in place.  The code does neither/both.

Take a look at fileinput.FileInput()  with the inplace option.  It makes 
it convenient to update text files "in place" by handling all the temp 
file copying and such.  It even handles iterating through the list of files.
> also you're shadowing the 'file' var, which might be confusing to beginners,
> as it's not the same file as in the outer for loop.
> Also, 'with' is a 3.0 keyword, right?  That's pretty interesting syntax,
> I've never seen it before, but I haven't used 3.x yet.
>
>   
Good point about 'file' as its a built-in name.  If the code ever has to 
use the std meaning, you have a problem.  Worse, it's unreadable as is.

With was introduced in 2.6, and does work nicely, at least in CPython.
>   
>>    for line in file:
>>      for setting in settings:
>>        if setting in line:
>>          if line[0] == '#':
>>            line = line[1:]
>>          else:
>>            line =  '#' + line
>>        output.write(line)
>>
>>     
>
> Also, you didn't define 'output' anywhere.  Is this an implicit declaration
> via the 'with' syntax?
>
> Thanks,
> -Luke
>
>   
No, output is an undefined global at present.  As I implied earlier, he 
was probably intending to have a separate file for writing.
>>     
> S.
>   
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>     
>
>   
Another potential  bug with the code is if more than one "setting" could 
appear in a line. It would change the line for an odd number, and not 
for an even number of matches.

Also, the nesting of output.write() is wrong, because file position 
isn't preserved, and random access in a text file isn't a good idea 
anyway.  But there's not much point in debugging that till the OP 
decides how he's going to handle the updates, via new files and copying 
or renaming, or via inputfile.


DaveA



More information about the Tutor mailing list