I am very new to python and writing a script that will extract a few URLs from two configuration files. The following is the body of the script as of now:
import os
import sys
import logging
logger = logging.getLogger('check_store')
logger.setLevel(logging.DEBUG)
env= raw_input("Enter environmentname (ex. dev/qa/prod): ")
cust= raw_input("Enter customer name: ")
engage_properties= '/opt/engage/engageconf.properties'
symmetric_properties= '/opt/engage/symmetric.properties'
with open ("%s" % (engage_properties)) as inF:
for line in inF:
if ("%s-%s.%sfqdn.com" % (env,cust,env)) in line:
print line
The output as as follows:
Enter environmentname (ex. dev/qa/prod): qa
Enter customer name: cust
connect.rest.address=http://connect.qa-cust.qafqdn.com
connect.rest.ssl.address=https://connect.qa-cust.qafqdn.com
connect.rest.giftregistry.service=http://connect.qa-cust.qafqdn.com:8280/services
receipt.server.host=engage.central.qa-cust.qafqdn.com
What I am trying to accomplish is having the script specifically look for the following as also shown above:
connect.rest.address=
connect.rest.ssl.address=
connect.rest.giftregistry.service=
and report back to the user if one of them is incorrect..
So, if i enter in when prompted: 'qa' for then env name and 'cust' for the customer name, if either of the URLs have anything other than something formatted like so:
connect.qa-cust.qafqdn.com
then it will tell the user which of the three URL variables are not formatted correctly.
So, to clarify.. if 'connect.rest.ssl.address=' did not equal the input that I provided (equaling qa-cust.qafqdn.com) but the rest of them did, then I would see an error like:
connect.rest.address - OK
connect.rest.ssl.address - ERROR: does not match value provided
connect.rest.giftregistry.service - OK
This script is basically a environment sanity checker.
I tried to make this as clear as possible and I appreciate the assistance.
I'm not sure I understood the question properly, but if you are expecting any line in the file to have the correct properties, then if the line has part of but not all of the correct formatting it is wrong.
with open ("%s" % (engage_properties)) as inF:
for line in inF:
if ("%s-%s.%srhythmforstores.com" % (env,cust,env)) in line:
print line
elif "rhythmforstores.com" in line:
print error_message
Related
So this function is a cut-out, from a class that should create and then extract information from an ini file. The problem I have is that the ini file definitely shows that all the added sections exist, but whenever I want the program to extract information or read from the file, it returns [], an empty list. I tried this function in a more basic version using Anaconda Navigator, well it turned out there it worked.
The screenshot shows the ini file.
As seen in the screenshot, the file is indeed not empty and the function successfully wrote to it, problem is whenever the function should print from it or when I want another function to read it, it returns [].
Code is as following:
class cSetup():
import os
import time
import datetime
import configparser as configparser
"""Class creates an ini file, this ini file contains a number of settings which can be read by the get function.
the program will later access this file to check for certain settings.
If the file is not existing yet, a function within the class will create it
"""
config = configparser.ConfigParser()
def write_setup(self):
if os.path.exists("Setup.ini"):
setup_file = open("Setup.ini", "r")
print(self.config.read(setup_file))
setup_file.close()
else:
"""This function is the initial setup, it writes all the necessary information to a .ini file."""
global config
"""Asks user for a name"""
Name = input("Please enter your name, note this can be changed in the settings""\n"
"Please enter the name here: ")
self.time.sleep(1)
"""asks user for prefered input method"""
PreferredInput = input("Input method required: 0 Shutdown, 1 Voice Commands, 2 Text Commands, 3 Dev Mode: ")
setup_file = open("Setup.ini", "w")
setup_file
self.config.write(setup_file)
self.config.add_section("Setup state")
self.config.set("Setup state", "Activated?", "True") # Convert to Bool later
section_option = "Settings"
self.config.add_section(section_option)
self.config.set(section_option, "Name", Name)
self.config.set(section_option, "Preferred Input", PreferredInput) # Convert to int later
self.config.write(setup_file)
setup_file = open("Setup.ini", "r")
print(self.config.read(setup_file))
setup_file.close()
I am trying to extract the source code line before and after the logging statement using astor and python AST, thanks to the answers available on my previous StackOverflow question:
import ast
import astor
import json
class LogPrinter(astor.TreeWalk):
def pre_Call(self):
if (isinstance(self.cur_node.func, ast.Attribute) and
isinstance(self.cur_node.func.value, ast.Name) and
(self.cur_node.func.value.id.lower() == "logging" or self.cur_node.func.value.id.lower() == "log" or self.cur_node.func.value.id.lower() == "logger")
):
print(astor.to_source(self.cur_node))
def post_Call(self):
if (isinstance(self.cur_node.func, ast.Attribute)):
print(astor.to_source(self.cur_node))
I can get logging statements from the above code but I am not able to get complete preceding and following statements:
example:
def db_contecton(string url):
if URL:
#multiline logger
logger.debug(
"connecting to
URL : " +url)
#multiline source code
db = db
.conn.
init()
db.connect(url)
#multiline logger
logger.
info("connection
to DB
successful")
The output that I am trying to get is:
1)
if url:
logger.debug("connecting to URL : " +url)
db = db.conn.init()
and
2)
db = db.conn.init()
db.connect(url)
logger.info("connection to DB successful")
NOTE: multiline loggers and source code is converted into single line
At this point I can extract loggers and get the following statement which does not have the complete source code:
my current output is
#the statement above logger is missing
logger.debug("connecting to URL : " +url)
db.conn.init() #the db variable is missing should be db = db.conn.init()
The above are just example snippets of python source code that may not be logically correct.
I'm not sure i understood your question: Do you want to parse python files as text and extract the 1 above and 1 below lines wherever it has some logging related code?
You could read the file as text, break it into lines, match with your desired words (e.g.: logger, logging, log), keep the indexes of those lines and then do whatever you want with it:
log_words = 'logger logging log'.split()
python_files = ['file1.py', 'file2.py']
keep = dict()
for f in python_files:
keep[f] = []
with open(f, 'r') as f:
lines = f.readlines()
for i in range(len(lines)):
for w in log_words:
if w in lines[i]:
keep[f].append(i - 1) # previous line
keep[f].append(i) # actual line
keep[f].append(i + 1) # next line
It checks each line for each desired word for each given file.
It's not performatic though.
But i believe it solves your problem.
I am having an issue getting my try and finally statement to execute properly. I am trying to get another Python file to execute once a user has interacted with the first program.For example, once the first program is run the user will be asked to scan their tag which will create a unique user id for that user; after their tag is scanned a second python file will be executed. My problem is that the second file is constantly being run as soon as the first file is executed regardless if the tag is scanned first or not. I have added my code below with comments to help explain better. Any thoughts?
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
# Second File being ran
import medform
reader = SimpleMFRC522()
try:
# user id being created
c = string.ascii_letters + string.digits
op = "".join(choice(c) for x in range(randint(8,16)))
# Printed before tag is scanned
print("Please Scan tag " )
reader.write(op + op)
# if tag is scanned / id created open second file
if reader.write(op + op):
os.system('python medform.py')
else:
print("Scan Tag First" )
# Print after tag is scanned
print("Scan Complete")
finally:
GPIO.cleanup()
importing a file runs it, there are 2 ways to do what you want:
import the file when you want it to run
define a main function in the other file that you can run from the first one instead of having all the code in the top level
the second option is the best one in most cases, as you normally would not want a file to actually do stuff on import.
so in the second file you would have:
def main():
# the code you want to run (make sure to indent it)
then in the first you can have:
import medform
# ...
medform.main()
Trying to write a script to simplify my cisco configs. User inputs names and passwords and the script will add them all together in a line by line document i can copy and paste from.
This is the method i've chosen (very new with python) and was wondering if there was a simpler way with functions or anything else?
hostname = input("Enter Hostname?" '\n')
en_secret = input("Enter Enable Password" '\n')
en_secret_script = "enable secret {}".format (en_secret)
hostname_script = "hostname {}".format(hostname)
script = '\n'.join([hostname_script, en_secret_script])
print(script)
You can get the same result with less line like this:
hostname = input("Enter Hostname?" '\n')
en_secret = input("Enter Enable Password" '\n')
print(f"hostname {hostname} \nenable secret {en_secret}")
I've created a tkinter program that writes the user's data to a file, but when writing the variable they turn into numbers.
This is what is being written to the file:
.15212688
.15213328
.15213232
INVALID REGISRATION NUMBER
And this is my code:
def show_entry_fields():#creates a function called show entry fields.
print("First Name: %s\nLast Name: %s\nRegistration number:%s" % (Fname.get(), Lname.get(), reg.get()))
if re.match('^[A-Za-z]{2}[0-9]{2}[A-Za-z]{3}$', reg.get()):#validates the users reg number by ching that its in the correct format
w.configure(text='That is a valid registration number')# if the reg is valid, tells user
else:
w.configure(text='Invalid registration number')#user is told that reg is not valid
data = open("invalid.txt", "w")#users data is writen to a file called 'invalid'
data.write(str(Fname))#first name
data.write('\n')#new line
data.write(str(Lname))#last name
data.write('\n')#new line
data.write(str(reg))# the casr's regitration number
data.write('\n')#new line
data.write('INVALID REGISRATION NUMBER')# the perpiose of being writen to the file
data.close()#closes the file when finished.
You should use
data.write(str(Fname.get()))#first name
data.write('\n')#new line
data.write(str(Lname.get()))#last name
data.write(str(reg.get()))
In your code you're converting objects to strings.