How to print the result of JSON to the output file? - python-3.x

The output of the JSON file has multiple responses like the one seen below
"response_code":1
"scan_date":"2011-07-27 03:44:56"
"permalink":"https://www.virustotal.com/gui/file/1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57/detection/f-1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57-1311738296"
"verbose_msg":"Scan finished, information embedded"
"total":43
"positives":19
The below code will get the value of "positives" in the JSON output and then print it to the file.
# DOES THE HASH EXISTS IN VT DATABASE?
if response == 0:
print(hash + ": UNKNOWN")
file = open(output,"a")
file.write(hash + " 0")
file.write("\n")
file.close()
# DOES THE HASH EXISTS IN VT DATABASE?
elif response == 1:
positives = int(json_response.get("positives"))
if positives >= 3:
print(hash + ": MALICIOUS")
file = open(output,"a")
file.write(hash + " " + str(positives))
file.write("\n")
file.close()
else:
print(hash + ": NOT MALICIOUS")
file = open(output,"a")
file.write(hash + " 0")
file.write("\n")
file.close()
else: print(hash + ": CAN NOT BE SEARCHED")
So the result of the current code will be something like the below
0136b7453cedf600d6f6aab7900901d3 19
I am trying to get the value of "permalink" in the JSON results and print it in the same output file. So the output must look like the below
0136b7453cedf600d6f6aab7900901d3 19 https://www.virustotal.com/gui/file/1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57/detection/f-1caea01fd9a6c6d12e5ca46007e25a4b1eff640060f45de8213e40aa5b47cd57-1311738296
How do I achieve this?
Thanks

You can read it the same way you read the positive values.
elif response == 1:
positives = int(json_response.get("positives"))
permalink = json_response.get("permalink")
if positives >= 3:`enter code here`
print(hash + ": MALICIOUS" + " | URL:" + permalink)
file = open(output,"a")`enter code here`
file.write(hash + " " + str(positives))
file.write("\n")
file.close()

Related

How to convert my loop into a function that I can call anytime

Good day. I have this snippet as a part of my script. I wanted to convert this into a function as this snippet is called a few times.
query = string-to-search-variable
for j in search(query, tld="co.in", num=5, stop=5, pause=2):
res = get_tld(j, as_object=True)
print(" " + "\t" + res.fld, end=" ")
You mean something like this so you can just call res_function(query)?
def res_function(query):
for j in search(query, tld="co.in", num=5, stop=5, pause=2):
res = get_tld(j, as_object=True)
print(" " + "\t" + res.fld, end=" ")

Keep getting else/elif invalid syntax error

Currently I'm writing a code where I want to ask motor values from motor controller using raspberry pi. However my code is throwing InvalidSyntax Error in else and elif statements. I've already read about if and elif statements in python, but I can't figure out mistake by myself. The code is below:
def motor_values():
while 1:
command_1 = '?A '+str(1)+' \r' #Asking first motor current
command_2 = '?A '+str(2)+' \r' #Asking second motor current
counter = 0
#First motor current
if counter = 0:
ser.write(command_1.encode()) #string to bytes
data_1 = ser.readline().decode().strip() #bytes to string
#Checking if data is received and extracting current value
if 'A=' in data_1:
value_1 = int(data_1.split('=')[1])
print("Motor Current(Channel 1): " + str((value_1) + " Ampers")
counter += 1
else:
print("Message is not received")
#Second motor current
elif counter == 1:
ser.write(command_2.encode()) #string to bytes
data_2 = ser.readline().decode().strip() #bytes to string
if 'A=' in data_2:
value_2 = int(data_2.split('=')[1])
print("Motor Current(Channel 2): " + str((value_2) + " Ampers")
counter += 1
else:
print("Message is not received")
else:
counter = 0
A few syntax errors here:
use == in the if clause condition
#First motor current
if counter == 0: #
remove one of the two ( in str((value_2)
print("Motor Current(Channel 1): " + str(value_1) + " Ampers")
print("Motor Current(Channel 2): " + str(value_2) + " Ampers")
you missed closing brace in print function
print("Motor Current(Channel 1): " + str(value_1) + " Ampers")

How to suppress exceptions when execute a SQL query in python

My project is to compare file names located on a folder with names saved in a PostgreSQL database.
I looked into different responses on the SO but nothing worked for me.
Please see below my comments within the source code.
try
cur = db_conn().cursor()
report query = "SELECT ev_report FROM stc_events_master WHERE
si_station_num = %s AND" +
" ev_ins_date BETWEEN to_date(" + "'" + "1/1/2018" + "'" + ",'mm/dd/yyyy')" + "
and TO_DATE('12/31/2018', 'mm/dd/yyyy')"
# files_dict content-> k = '123p34" , value = "DV03S_120124_5-7-2018.pdf"
for k, v in files_dict.items():
cur.execute(report_query, (k,))
# the reports are unique in the database table
query_result = cur.fetchmany(1) #incoming value:DV03S_120124_5-7-2018.pdf
# query returns:
sta = str(query_result[0])
# if a file is not found in the database, the exception happens
# and the code below is not executed. It jumps
# directly to Exception
if len(sta) < 1:
print("no report found in the database")
print("query_results" + sta)
else:
if v.lower() == q_ry.lower():
print("match " + v)
else:
print("no match " + v)
except Exception:
pass
print("In Exception area")
finally:
cur.close()
I want to continue the loop even if nothing is found the database and save a name of the file from the folder which caused the exception. Now, the code stops after the exception.
Thank you for your help.
for k, v in files_dict.items():
cur.execute(report_query, (k,v))
if cur.rowcount == 0:
print("The file is not in the database: " + v)
else:
query_result = cur.fetchmany(3)
sta = str(query_result[0])
file_name_length = len(sta)
q_ry = sta[2: file_name_length-3]
if v.lower() == q_ry.lower():
pass
else:
print("no match after comparing names" + v)
except (Exception, psycopg2.Error) as error:
print("Error fetching data from PG table " + k, error)
finally:
cur.close()

moving between indexes in a list in python

In Python, I populate info from a file to a list and then print the first index in the list, now I want to print the next index from the list without multiple my code.
How can I promote the index i'm printing?
question = open("questions.txt", "r")
print(question.readlines()[0])
tanswer = open("answers.txt", "r")
correct_answer = float(tanswer.readlines()[0])
uanswer = float(input("Write the answer: "))
if correct_answer==uanswer:
print("Amazing " + str(correct_answer) + " is the correct answer")
else:
print("Wrong " + str(uanswer) + " is not correct, Try again please. ")
As far as I understood, you are trying to split the lines.
let's say
line = '1000 2000 3000'
line = line.split(' ')
then you will get line[0]
Try this I hope this helps.
Use zip:
with open("questions.txt") as ques, open("answers.txt") as ans:
for q, a in zip(ques, ans):
print(q)
uanswer = input("Write the answer: ")
if float(a) == float(uanswer):
print("Amazing " + str(a) + " is the correct answer")
else:
print("Wrong " + str(uanswer) + " is not correct, Try again please. ")

Getting the Error Despite Correct Output

getting this error meassage despite having exactly same output as expected output.
* ERROR: Expected to find a number in the line Available Letters: abcdefghijklmnopqrstuvwxyz.
Check to be sure your lines match up with the expected output!!! *
MY CODE:
def hangman(secretWord):
print ("Welcome to the game, Hangman!")
print ("I am thinking of a word that is " + str(len(secretWord)) + " letters long" )
lettersGuessed=[]
guesses = 8
p = " "
while guesses > 0:
print ("You have " + str(guesses) + " guesses left")
print ("Available Letters: " + str(getAvailableLetters(lettersGuessed))),
user_input = input("Please guess a letter: ")
user_input = str(user_input)
user_input = user_input.lower()
if user_input in lettersGuessed:
print ("Oops! You've already guessed that letter: " + str(getGuessedWord(secretWord, lettersGuessed)))
else:
lettersGuessed.append(user_input)
if user_input in secretWord:
print ("Good guess: " + str(getGuessedWord(secretWord,lettersGuessed)))
if isWordGuessed(secretWord, lettersGuessed):
break
else: continue
else:
print("Oops! That letter is not in my word: " + str(getGuessedWord(secretWord, lettersGuessed)))
guesses = guesses - 1
p = str(getGuessedWord(secretWord, lettersGuessed))
p = p.split(" ")
p = "".join(p)
p = str(p)
if p == secretWord:
print ("Congratulations, you won!")
return
else:
print ("Sorry, you ran out of guesses. The word was " + secretWord + ".")
return
Check each line and "be sure your lines match up with the expected output".
It's possible the automated system that is checking the output requires the lines of output must exactly match their "correct output" including the ----------- lines, and you're code doesn't print those lines.
Easy as:
print ("I am thinking of a word that is " + str(len(secretWord)) + " letters long" )
print ("-----------") ### <---- Add this one line
lettersGuessed=[]
and
print ("Good guess: " + str(getGuessedWord(secretWord,lettersGuessed)))
print ("-----------") ### <---- Add this one line
if isWordGuessed(secretWord, lettersGuessed):
It's possible that you'll need to add that one line in other conditions within the code, as in the else: conditions.
And as always to make debugging easier, less repetition and cleaner code, you could assign that output to a variable and print it when needed:
def hangman(secretWord):
line_break = "-----------"
...
print ("I am thinking of a word that is " + str(len(secretWord)) + " letters long" )
print (line_break)
, etc.
Hope this helps.

Resources