Python search through file
I'm working on a python script that tries to add itself to startup on Linux via ~/.bashrc. I want the script to search through ~/.bashrc to see if it's already added. If it is then I just want to continue with normal execution. If not, I want it to add itself to ~/.bashrc then continue. This is what I'm currently trying:
fname = sys.argv[0]
fpath = os.getcwd()
homepath = os.getenv("HOME")
startupfile = homepath + "/.bashrc"
fileopen = open(startupf开发者_运维百科ile, 'r')
for line in fileopen:
if fname in line:
break
else:
os.system('echo "python ' + fpath + '/' + fname + ' &" >> ' + startupfile)
break
fileopen.close()
Only problem is, it adds a lot of itself to ~/.bashrc. Like a hundred or so. I want it to just add once so the script runs on startup.
In general it might not be a good idea to add a python script itself to startup on Linux via ~/.bashrc
.
import fileinput
import os
# assume script name is unique in the .bashrc context
uniqkey = os.path.basename(__file__)
startupfile = os.path.expanduser('~/.bashrc')
startupline = 'python %s &\n' % os.path.abspath(__file__)
written = False
for line in fileinput.input(startupfile, inplace=1):
if uniqkey in line:
if not written:
written = True
print startupline, # rewrite
#else do nothing (it removes duplicate lines)
else:
print line,
if not written: # add startup line if it is not present
open(startupfile,'a').write('\n'+startupline) # ignore possible race condition
you need to search the whole file and then either add the line or not, as the loop you have only checks the first line. because it break the loop right after either finding or not finding the name on the line.
you want:
found = False
for line in fileopen:
if fname in line:
found = True
break
if not found:
os.system('echo "python ' + fpath + '/' + fname + ' &" >> ' + startupfile)
second problem is that fname in line
isn't the same as line.find(fname) > -1
found = False
for line in fileopen:
if line.find(fname) > -1:
found = True
break
if not found:
os.system('echo "python ' + fpath + '/' + fname + ' &" >> ' + startupfile)
Why are you opening the file if you don't use python functions?
os.system('echo "python ' + fpath + '/' + fname + ' &" >> ' + startupfile)
is never a good idea. You are not even using Python's IO functions.
And your problem is at your for loop, you are appending it when fname not in line, thats why it writes it hundred times.
The code should be like:
command="python run.py"
startupfile="bashrc"
f=open(startupfile,"r")
found=False
for line in f:
if command in line:
found=True
break
f.close()
if not found:
f=open(startupfile,"a")
f.write(command)
f.close()
And read: http://docs.python.org/tutorial/inputoutput.html
精彩评论