Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Code Review Help
#1
Hi there,

So I have some code that I wrote to assist me in deploying headless pi's. I am a complete Python newb but I wrote this up and have some questions on what could have been done better.

import os
import sys
import fileinput
import shutil


os.chdir('/home/daniel/Documents/python_work/headlesspi/')
shutil.copyfile('interfaces', 'mypi/interfaces')

print("File Copy Done")

textToSearch = "172.168.0.0"

print ("Assign IP Address:")
textToReplace = input( "> " )

os.chdir('/home/daniel/Documents/python_work/headlesspi/mypi/')
fileToSearch = 'interfaces'

tempFile = open( fileToSearch, 'r+' )
for line in fileinput.input( fileToSearch ):
    if textToSearch in line :
        print('Match Found')
    else:
        print('Match Not Found!!')
    tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()


input( '\n\n Press Enter to exit...' )
The code works but I have a few adjustments I need to make.

1.) when I insert the sd card it normally mounts it to /media/daniel/ I need to change the directory where it copies the original vanilla interfaces file to the mounted files system. Something like /media/mount/rootfs/etc/interfaces.

Any how I would like someone to look over my code and if it could have been done better point me in the right direction.

Thanks,
Reply
#2
Some simple stuff
Don't need to import sys, it's never used
Syntax is OK,
I would encapsulate with functions
Reply
#3
I don't see the need for using fileinput for a single file. in any case - you should use with context manager.
replace
tempFile = open( fileToSearch, 'r+' )
for line in fileinput.input( fileToSearch ):
    if textToSearch in line :
        print('Match Found')
    else:
        print('Match Not Found!!')
    tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()
with one of
with open(fileToSearch, 'r+') as temp_file
    for line in temp_file:
        if textToSearch in line :
            print('Match Found')
        else:
            print('Match Not Found!!')
        temp_file.write(line.replace(textToSearch, textToReplace))
or

with fileinput.input(fileToSearch, mode='r+') as temp_file:
    for line in temp_file:
        if textToSearch in line :
            print('Match Found')
        else:
            print('Match Not Found!!')
        temp_file.write( line.replace(textToSearch, textToReplace))
Reply
#4
In general you will find that the habit of hard-coding values such as file paths and search text will bite you in the butt frequently. You don't necessarily have to do command-line parsing (though that's an option) but I would at least put the base path in a variable.

Why are your printing out whether you found a match or not? Is that for debugging?

There is no error handling.

I wouldn't bother making the user hit enter when its done; either print a success message and exit or print nothing. The latter option only really makes sense when there is error handling i.e., if the script doesn't complain about anything it must have been successful.

Here's my take on it..
import os
import sys
import fileinput
import shutil
 
BASE_PATH = '/home/daniel/Documents/python_work/headlesspi/'

if __name__ == "__main__":
    try:
        os.chdir(BASE_PATH)
        print("Copying files....", end='')
        shutil.copyfile('interfaces', 'mypi/interfaces')
        print("done")
 
        textToSearch = "172.168.0.0"
 
        textToReplace = input( "Assign IP Address: > " )
 
        os.chdir(os.path.join(BASE_PATH,'mypi'))
        fileToSearch = 'interfaces'
 
        tempFile = open( fileToSearch, 'r+' )
        for line in fileinput.input( fileToSearch ):
            if textToSearch in line :
                print('Match Found')
            else:
                print('Match Not Found!!')
            tempFile.write( line.replace( textToSearch, textToReplace ) )
        tempFile.close()
     except Exception as e:
        print("Could not process files: {0}".format(e))
 
Reply
#5
All,

thank you!! I will work on this over the weekend and post. I appreciate the feedback.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  First web scraping project using bs4, review my code OhNoSegFaultAgain 2 2,931 Mar-30-2019, 04:45 PM
Last Post: OhNoSegFaultAgain
  Code review needed for a basic repl implementation RickyWilson 2 2,839 Dec-27-2017, 02:20 PM
Last Post: mpd

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020