import os
import sys
import re
import string
f=open('./iprange','r')
s=f.readline()
f.close()
pattern='inet addr:'+s
pattern=pattern.split('x')[0]
pattern='('+pattern+'...'+')'
os.system('ifconfig -a >> interfaces')
f=open('./interfaces','r')
s=f.readline()
while (len(s))!=0:
i=re.search(pattern,s)
if i!=None:
sp=re.split(pattern,s)[1]
ip=re.split('inet addr:',sp)[1]
break
s=f.readline()
f.close()
os.system('rm ./interfaces')
f=open('./userip','w')
f.write(ip)
f.close()
NameError;name 'ip' is not defined
I split pattern by s and store the result in sp, then I find the IP address and store the result in ip. But the error says ip is not defined - what's going on?
while (len(s))!=0:
i=re.search(pattern,s)
if i!=None:
sp=re.split(pattern,s)[1]
ip=re.split('inet addr:',sp)[1]
break
s=f.readline()
The ip assignment is inside the if closure, which is apparently never being executed.
I'd do something more like this:
import os
import sys
import re
from itertools import takewhile
with open('./iprange','r') as f:
s = f.readline()
prefix = 'inet addr:'
pattern = prefix + s
pattern = pattern.split('x')[0]
pattern = '(%s...)' % pattern
os.system('ifconfig -a >> interfaces')
with open('interfaces', 'r') as f:
# Put all lines up to the first empty line into a list
# http://docs.python.org/2/library/itertools.html#itertools.takewhile
# `[line.rstrip() for line in f]` could be a generator instead:
# (line.rstrip() for line in f)
lines = list(takewhile(lambda x: x, [line.rstrip() for line in f]))
os.remove('interfaces')
for s in lines:
if re.search(pattern, s):
sp = re.split(pattern, s)[1]
ip = sp[len(prefix):]
with open('./userip', 'w') as f:
f.write(ip)
break
else:
print "No match found"
For one thing, you only write to the file userip if you find a match and you get a message if no match was found.
Related
Basically it is supposed to search a txt file for a string and capitalize it. I have gotten this far with some help from stack overflow but anything I try doesn't work.
import os, fileinput
import sys, subprocess
prompt = "> "
print("text to search for: ")
string1 = input(prompt)
with open(os.path.expanduser("/users/acarroll55277/documents/notes/new_myfile.txt"), 'r+') as f:
matches = list()
[matches.append(i) for i, line in enumerate(f.readlines()) if string1 in line.strip()]
f.write(f.replace(string1, string1.capitalize))
if len(matches) == 0: print(f"string {string1} not found")
[print(f"string {string1} found in line{i}") for i in matches]
and this is the error message I get
AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'
you had some redundant function calls, and some errors such as not using () on capitalize and calling replace on a file object instead of on a string.
try this:
import os, fileinput
import sys, subprocess
prompt = "> "
print("text to search for: ")
string1 = input(prompt)
with open(os.path.expanduser("/users/acarroll55277/documents/notes/new_myfile.txt"), 'r+') as f:
matches = [line.replace(string1,string1.capitalize()) for line.strip() in f.readlines() if string1 in line]
f.writelines(matches)
if len(matches) == 0: print(f"string {string1} not found")
for i in matches:
print(f"string {string1} found in line{i}")
Input string is something like this
$sim,abad_x_y,rat,2,3,a,b
123,456,1345
323,455,2433
$sim,abad_z_c,rat,2,3,c,d
123,4456,1345
323,4554,2445
Output
$sim,abad_x_y,rat,2,3,x,y
123,456,1345
323,455,2433
$sim,abad_z_c,rat,2,3,z,c
123,4456,1345
323,4554,2445
From second token of $sim line x,y should be taken and replaced a,b at the end
import os
import sys
import re
fin=open('old_file.txt','r')
fout=open('new_file.txt','a')
line_list = fin.readlines()
for w in line_list.rstrip('\n\r'):
if w.startswith('$sim'):
word_set=w.split(',')
split_zone=word_set[1].split('_')
fout=fout.write(w.replace(word_set[-1],split_zone[-1]))
fout=fout.write(w.replace(word_set[-2],split_zone[-2]))
fout=fout.write(w)
fin.close()
fout.close()
import os
import sys
import re
fin=open('old_file.perf','r')
fout=open('new_file.txt','w')
line_list = fin.readlines()
for line in line_list:
if line.startswith('$sim'):
word_set=line.split(',')
split_zone=word_set[1].split('_')
new_line=line.replace(word_set[-1],split_zone[-1])
new_line2=new_line.replace(word_set[-2],split_zone[-2])
fout.write(new_line2)
fout.write('\n')
else:
fout.write(line)
fin.close()
fout.close()
I have 2 numbers in two similar files. There is a new.txt and original.txt. They both have the same string in them except for a number. The new.txt has a string that says boothNumber="3". The original.txt has a string that says boothNumber="1".
I want to be able to read the new.txt, pick the number 3 out of it and replace the number 1 in original.txt.
Any suggestions? Here is what I am trying.
import re # used to replace string
import sys # some of these are use for other code in my program
def readconfig():
with open("new.text") as f:
with open("original.txt", "w") as f1:
for line in f:
match = re.search(r'(?<=boothNumber=")\d+', line)
for line in f1:
pattern = re.search(r'(?<=boothNumber=")\d+', line)
if re.search(pattern, line):
sys.stdout.write(re.sub(pattern, match, line))
When I run this, my original.txt gets completely cleared of any text.
I did a traceback and I get this:
in readconfig
for line in f1:
io.UnsupportedOperationo: not readable
UPDATE
I tried:
def readconfig(original_txt_path="original.txt",
new_txt_path="new.txt"):
with open(new_txt_path) as f:
for line in f:
if not ('boothNumber=') in line:
continue
booth_number = int(line.replace('boothNumber=', ''))
# do we need check if there are more than one 'boothNumber=...' line?
break
with open(original_txt_path) as f1:
modified_lines = [line.startswith('boothNumber=') if not line
else 'boothNumber={}'.format(booth_number)
for line in f1]
with open(original_txt_path, mode='w') as f1:
f1.writelines(modified_lines)
And I get error:
booth_number = int(line.replace('boothNumber=', ''))
ValueError: invalid literal for int() with base 10: '
(workstationID="1" "1" window=1= area="" extra parts of the line here)\n
the "1" after workstationID="1" is where the boothNumber=" " would normally go. When I open up original.txt, I see that it actually did not change anything.
UPDATE 3
Here is my code in full. Note, the file names are changed but I'm still trying to do the same thing. This is another idea or revision I had that is still not working:
import os
import shutil
import fileinput
import re # used to replace string
import sys # prevents extra lines being inputed in config
# example: sys.stdout.write
def convertconfig(pattern):
source = "template.config"
with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
for line in file:
match = r'(?<=boothNumber=")\d+'
sys.stdout.write(re.sub(match, pattern, line))
def readconfig():
source = "bingo.config"
pattern = r'(?<=boothNumber=")\d+' # !!!!!!!!!! This probably needs fixed
with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
for line in file:
if re.search(pattern, line):
fileinput.close()
convertconfig(pattern)
def copyfrom(servername):
source = r'//' + servername + '/c$/remotedirectory'
dest = r"C:/myprogram"
file = "bingo.config"
try:
shutil.copyfile(os.path.join(source, file), os.path.join(dest, file))
except:
print ("Error")
readconfig()
# begin here
os.system('cls' if os.name == 'nt' else 'clear')
array = []
with open("serverlist.txt", "r") as f:
for servername in f:
copyfrom(servername.strip())
bingo.config is my new file
template.config is my original
It's replacing the number in template.config with the literal string "r'(?<=boothNumber=")\d+'"
So template.config ends up looking like
boothNumber="r'(?<=boothNumber=")\d+'"
instead of
boothNumber="2"
To find boothNumber value we can use next regular expression (checked with regex101)
(?<=\sboothNumber=\")(\d+)(?=\")
Something like this should work
import re
import sys # some of these are use for other code in my program
BOOTH_NUMBER_RE = re.compile('(?<=\sboothNumber=\")(\d+)(?=\")')
search_booth_number = BOOTH_NUMBER_RE.search
replace_booth_number = BOOTH_NUMBER_RE.sub
def readconfig(original_txt_path="original.txt",
new_txt_path="new.txt"):
with open(new_txt_path) as f:
for line in f:
search_res = search_booth_number(line)
if search_res is None:
continue
booth_number = int(search_res.group(0))
# do we need check if there are more than one 'boothNumber=...' line?
break
else:
# no 'boothNumber=...' line was found, so next lines will fail,
# maybe we should raise exception like
# raise Exception('no line starting with "boothNumber" was found')
# or assign some default value
# booth_number = -1
# or just return?
return
with open(original_txt_path) as f:
modified_lines = []
for line in f:
search_res = search_booth_number(line)
if search_res is not None:
line = replace_booth_number(str(booth_number), line)
modified_lines.append(line)
with open(original_txt_path, mode='w') as f:
f.writelines(modified_lines)
Test
# Preparation
with open('new.txt', mode='w') as f:
f.write('some\n')
f.write('<jack Fill workstationID="1" boothNumber="56565" window="17" Code="" area="" section="" location="" touchScreen="False" secureWorkstation="false">')
with open('original.txt', mode='w') as f:
f.write('other\n')
f.write('<jack Fill workstationID="1" boothNumber="23" window="17" Code="" area="" section="" location="" touchScreen="False" secureWorkstation="false">')
# Invocation
readconfig()
# Checking output
with open('original.txt') as f:
for line in f:
# stripping newline character
print(line.rstrip('\n'))
gives
other
<jack Fill workstationID="1" boothNumber="56565" window="17" Code="" area="" section="" location="" touchScreen="False" secureWorkstation="false">
The bingo.config has a string with a random integer in it.
Inside the file, it looks like
boothNumber="2"
My template.config file has the same string with a different integer or number.
I am trying to replace this with the current integer in bingo.config
My problem is that the number in template.config is not being replaced by the number in bingo.config
It's replacing the number in template.config with the literal string "r'(?<=boothNumber=")\d+'"
So template.config ends up looking like
boothNumber="r'(?<=boothNumber=")\d+'"
instead of
boothNumber="2"
It looks like my issue is stemming from how I save the variable "pattern" in the "readconfig" function.
Any ideas on how I can save the integer from bingo.config into a proper variable that can be used?
import os
import shutil
import fileinput
import re # used to replace string
import sys # prevents extra lines being inputed in config
# example: sys.stdout.write
def convertconfig(pattern):
source = "template.config"
with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
for line in file:
match = r'(?<=boothNumber=")\d+'
sys.stdout.write(re.sub(match, pattern, line))
def readconfig():
source = "bingo.config"
pattern = r'(?<=boothNumber=")\d+' # !!!!!!!!!! This probably needs fixed
with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
for line in file:
if re.search(pattern, line):
fileinput.close()
convertconfig(pattern)
def copyfrom(servername):
source = r'//' + servername + '/c$/remotedirectory'
dest = r"C:/myprogram"
file = "bingo.config"
try:
shutil.copyfile(os.path.join(source, file), os.path.join(dest, file))
except:
print ("Error")
readconfig()
# begin here
os.system('cls' if os.name == 'nt' else 'clear')
array = []
with open("serverlist.txt", "r") as f:
for servername in f:
copyfrom(servername.strip())
I'm using Python Fabric, trying to comment all lines in a file that begin with "#", unless that "#" is followed by 2 specific IP addresses. So if the file contains (without the bullets)
#hi
#IP1
some stuff here
#IP2
then the resulting file should be (also without the bullets)
##hi
#IP1
some stuff here
#IP2
This is what I have so far:
def verify():
output = sudo("/sbin/service syslog status")
#if syslog is running
if 'is running...' in output:
#then set output to the value of the conf file
output = sudo("cat /etc/syslog.conf")
#If pattern is matched
if "#" in output and not "#IP1" and not "#IP2":
#read all the lines in the conf file
sys.stdout = open('/etc/syslog.conf', 'r+').readlines()
#and for every line, comment if it matches pattern
for line in sys.stdout:
if "#" in line and not "#1P1" and not "#IP2":
line = "#" + line
else:
print GOOD
else:
print RSYSLOG
I get that when I say
if "#" in output and not "#IP1" and not "#IP2"
Python is thinking that I am saying "do some thing if there is an # in the file, but ONLY if you also do not have #IP1 and #IP2." What I'm trying to say is "do some thing to any line starting with an #, except the lines #IP1 and #IP2." Also I know there are other errors in my code, but I'm working on just this now.
thanks.
Regex solution:
You can use the following regex to match:
^(?=#(?!(IP1|IP2)))
And replace with #
See DEMO
Code:
re.sub(r'^(?=#(?!(IP1|IP2)))', r'#', myStr)
I would do like,
if not "#IP1" in output or not "#IP2" in output:
if output.startswith("#"):
// stuff here
Check if criteria exists in the glob, and if so, open file, read line-by-line, and use re.sub() to add a # inline to the lines that require it.
import re
ip1 = '1.1.1.1'
ip2 = '2.2.2.2'
fh = open('in.txt', 'r')
f = fh.read()
fh.close()
if re.search(r'(#(?!({0}|{1})))'.format(ip1, ip2), f):
fh = open('in.txt', 'r')
for line in fh:
line = re.sub(r'^(#(?!({0}|{1})))'.format(ip1, ip2), r'#\1', line)
print(line)
Input file:
#1.1.1.1
#this
#2.2.2.2
#3.3.3.3
#
no #
blah
Output:
#1.1.1.1
##this
#2.2.2.2
##3.3.3.3
##
no #
blah