This question already has answers here:
String comparison doesn't seem to work for lines read from a file
(2 answers)
Closed 5 years ago.
I'm trying to write a small Python script to generate CentOS7 kickstart configs. I have a skeleton config file and based on some user inputs, the script will pop out a custom cfg file by inserting the customized blocks into the skeleton. However, the string comparison is not working for some reason.
#!/usr/bin/python
type = raw_input("Static OR DHCP: ")
gateway = raw_input("Gateway IP: ")
nameserver = raw_input("DNS Server: ")
hostname = raw_input("Hostname: ")
ipaddr = raw_input("IP Address: ")
skeleton = open('ks_skeleton.cfg', 'r')
config = open(hostname + '.cfg', 'w')
for line in skeleton:
if line == "$NETWORK":
print("Interting Network values...");
config.write("network --bootproto=" + type + " --device=ens192 --gateway=" + gateway + " --ip=" + ipaddr + " --nameserver=" + nameserver + " --netmask=255.255.255.0 --ipv6=auto --activate\n");
config.write("network --hostname=" + hostname + "\n");
else:
config.write(line);
The lines that you read from skeleton have new lines at the end, so the exact string comparison are probably not going to work. If you do line = line.strip() as the first line of your loop it will remove whitespace from before and after any text on the line, and might get you closer to what you want.
Related
This question already has answers here:
TypeError: can only concatenate str (not "float") to str
(3 answers)
Closed 2 years ago.
import time
print("><><><><><><><><><><><><><")
print("> Reaction Time Tester <")
print("><><><><><><><><><><><><><")
name = input ("Please enter your first name: ")
time.sleep(1)
start=time.time()
text = input("Press enter on keyboard")
end = time.time()
duration = round(end-start,2)
print("Reaction Time: " + str(duration)+ "seconds.")
#Saving the results to a csv file
csv = (name + "," + duration + "/n")
win = open ("ClickTestResults.csv","a")
win.write(csv)
win.close()
time.sleep(60)
This is the error it shows when I run it:
Traceback (most recent call last):
File "C:\Users\theun\Desktop\click test.py", line 20, in
csv = (name + "," + duration + "/n")
TypeError: can only concatenate str (not "float") to str
csv = (name + "," + str(duration) + "/n")
or better
csv = f'{name},{duration}\n'
Edit: context added per comment advise from Carlo Zanocco
In the first example I kept the original format of the code, but the duration value is not a string and can not be concatenated with the other strings, so it is wrapped in the str function.
The second example is considered "better" because the formatting is easier to read and the duration is automatically converted to a string in the process.
Python - PING a list of IP Address from database
I have a list of ip addresses consisting of 200 locations, which in that location there are 4 ip addresses that I need to do ping testing. I intend to make a command which when I write the name or code of a particular location then it will directly ping to 4 ip address at that location. I have learned a bit to create a list that contains the ip address I entered through the command input () like this :
import os
import socket
ip = []
y = ['IP 1 : ','IP 2 : ', 'IP 3 : ', 'IP 4 : ']
while True:
for x in y:
server_ip = input(x)
ip.append(server_ip)
break
for x in ip:
print("\n")
rep = os.system('ping ' + x + " -c 3")
please give me a little advice about the command I want to make so that I no longer need to enter the ip address one by one. which still makes me confused, especially on how to make the existing items in the database into a variable x which we will insert into this command;
rep = os.system ('ping' + x + "-c 3")
EDIT: It now iterates over a CSV file rather than a hard-coded Python dictionary.
I believe you will be better off using python dictionaries rather than python lists. Assuming you are using Python 3.X, this is what you want to run:
import os
import csv
# Save the IPs you want to ping inside YOURFILE.csv
# Then iterate over the CSV rows using a For Loop
# Ensure your ip addresses are under a column titled ip_address
with open('YOURFILE.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
rep = os.system("ping " + row['ip_address'] + " -c 3")
This is my code, in TestHash.py, and it won't compile. When I type python TestHash.py nothing prints on the command line.
#import Hash.py
from Hash import *
def testHash(radix, modulus, fName):
print("Using radix " + str(radix) + " and modulus " + str(modulus) + ".")
print(" Input | hash value")
file = open(fName)
for line in file:
for word in line.strip().split(' '):
if (word != ''):
print('{0:10s} {1:8d}'.format(word, hash(word, radix, modulus)))
If this is your whole program, then the program is actually running. It does not seem to run because everything is inside a function. The function is not automatically run - you need to call it to run it.
To call the function add this line to the end of your code:
testHash(radix, modulus, fName)
replacing radix, modulus, and fName with the proper values.
So I am attempting to write a script that has a number of user defined variables. I've gotten to the final step and can't seem to get it to dissolve things properly.
Purpose: The script should let me define a shapefile/layer file, a distance for the buffer to work with, create the buffer then dissolve it (This is where it fails) and save.
Here is what I have so far.
import arcpy
from arcpy import env
env.workspace = "C:\Users\...\Conroe Cut"
fc = raw_input (' What file is being Buffered' + " ")
distance = raw_input (' Buffer Size' + " ")
finalfile = raw_input (' Name of Final File' + " ")
unique_name = arcpy.CreateUniqueName("Results\\"+finalfile)
arcpy.Buffer_analysis(fc, unique_name, distance)
arcpy.Dissolve_management(unique_name, "SINGLE_PART", "DISSOLVE_LINES")
print "Finished with Analysis"
You can perform the buffer and dissolve in one line using arcpy.Buffer_analysis--make sure to specify the "ALL" parameter, which performs the dissolve. This should significantly simplify and clean your script.
import arcpy
infc = r'C:\path\to\input\shapefile.shp'
outfc = r'C:\path\to\output\shapefile_buffered_dissolved.shp'
bufferDistance = 20
arcpy.Buffer_analysis(infc, outfc, bufferDistance, "", "", "ALL")
first time posting here. I have searched high and low to figure out a way to do this, but I either don't understand how to apply existing answers to my code.
What I am trying to do is this: I want to take user input (a year), make sure it's between a range of years, and then if it is, concatenate it with an existing string as a variable.
The result of this code is that I get through and give all the necessary inputs, and then it fails with "fullInstr = str("cp -r /mnt/data/archive"+ fquery+ "/" + yquery+mquery+dquery+"/"+hquery+"*" + " " + outl2)
TypeError: cannot concatenate 'str' and 'int' objects"
import os
import sys
os.system("clear")
overW = str("0")
outf = str("/autocopy.sh") # Output file full path and file name
if os.path.isfile("/autocopy.sh"): #
overW = raw_input("This will overwrite the previous version. Do you want to continue? (y/n) ")
os.system("clear")
else:
os.system("clear")
if overW != "y":
os.system("clear")
sys.exit("No changes made.\n\n")
else:
os.system("clear")
#! Could also prompt for output file name, depending on how army-proof this needs to be.
finishMessage = "Finished."
outl = str("0") # Copy-to location
outl2 = str("0") # Modified Copy-to location
fquery = str("0") # A or B location variable
yquery = int("0") # Year variable
mquery = int("0") # Month variable
dquery = int("0") # Day variable
hquery = str("0") # Hour variable
mh1 = int("0") # Modified starting hour after transformation
mh2 = int("0") # Modified ending hour after transformation
mpath = str("0") # makes path if needed
fullInstr = str("0") # Full command set to write to file
formatList = (['A', 'B'])
yearList = list(range(2000,2099))
#monthList = (['01']-['12'])
#! hquery is going to have to parse for ranges
# Instruction header
print "Builds a script to automatically copy folders and files from the storage array to a location of your choosing.\n"
print "Valid inputs for the questions below are numeric."
print "Year would be the full year, i.e. 2013"
print "Month is the two-digit month, i.e. 10"
print "Day is the two-digit day, i.e. 22"
print "Hour or hour range is just the first two digits of the hours you want to copy. i.e. 15 or 00-23\n\n"
outl = raw_input("Where do you want to copy the files to? Type the full path: ")
while not os.path.exists(outl):
mpath = raw_input ("\nThat path doesn't exist on this system. Do you want to create it? (y/n) ")
if mpath != "y":
outl = raw_input("Where do you want to copy the files to? Type a valid path: ")
else:
os.mkdir(outl)
print "\n"
if not outl.endswith("/"):
outl2 = outl + "/"
fquery = raw_input("Do you want to copy A or B? ")
while not(fquery in formatList):
print "\nInvalid input. You have to choose one of the two as printed above."
fquery = raw_input("\nDo you want to copy A or B? ")
print "\n"
yquery = int(raw_input("What year? "))
while yquery not in yearList:
print "\nInvalid input. You have to choose a year in this century."
yquery = int(raw_input("\nWhat year? "))
print "\n"
mquery = raw_input("What day? ")
#! Valid months are 01 to 12
dquery = raw_input("What day? ")
#! Valid days are 01 to 31
hquery = raw_input("What hour or hour range? ")
#! if input is greater than two characters is must contain a - character
#! if is not 00-23, separate first and last numbers and write a line for each. If it isn't a range, don't transform it.
#os.system("touch " + outf)
#! if no error keep going
fullInstr = str("cp -r /mnt/data/archive"+ fquery+ "/" + yquery+mquery+dquery+"/"+hquery+"*" + " " + outl2)
os.system("echo "+fullInstr+ "> /autocopy.sh")
#os.system("chmod u+x "+outf) # Makes the output file executable
#! if error = 0 set finishMessage to print "Your shell script is complete and is ready to run. Run it by typing ." + outf
#! if error is <> 0 set finishMessage to print "Wasn't able to make the output file executable automatically. Use chmod to modify the file permissions manually on the file "+outf
#os.system("clear")
print finishMessage+"\n\n"
Stuff that is commented out is either not working or not implemented yet. I know the code quality is probably not the best, but this is my first time coding to do something I require. I have tried a lot of things like yquery = str(yquery) or just changing the fullInstr string to have str(yquery) in it and I can not get it to work. I am becoming frustrated.
You should use format for string formatting to avoid worrying about the type of variable being concatenated.
fullInstr = "cp -r /mnt/data/archive/{0}/{1}{2}{3}/{4}* {5}".format(fquery,yquery,mquery,dquery,hquery,out12)
That is because you need to convert the int to a str object.
fullInstr = str("cp -r /mnt/data/archive" + fquery + "/" + str(yquery) + mquery + dquery + "/" + hquery + "*" + " " + ^
outl2) ^
# ^ -> Use str to convert
The above code worked on my machine. Running windows 8. Python 2.7.5. I just had to change clear to cls.