Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I created a Python script which displays all passwords that are stored on the computer by calling external commands by using the subprocess module.
I just want to get all passwords that are stored on my computer, but when I executed the script I get an error instead of getting the result:
TypeError: argument of type 'int' is not iterable
Here is my code:
import subprocess
data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles'])
data.decode('utf-8').split('\n')
profiles = [x.split(':')[1][1:-1] for x in data if 'All User Profile' in x]
for i in profiles:
results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 'key=clear'])
results.decode('utf-8').split('\n')
results = [y.split(':')[1][1:-1] for y in results if 'Key Content' in y]
try:
print('{:<30}| {:<}'.format(i, results[0]))
except IndexError:
print('{:<30}| {:<}'.format(i, ''))
data.decode('utf-8').split('\n') is producing a nice list, but it doesn't put that list into the variable data, you need to reassign the process to data and do the same for results
data = data.decode('utf-8').split('\n')
results = results.decode('utf-8').split('\n')
There may be other issues but this will account for why what you thought was a list of strings is actually still the bytes object so you are iterating over the byte (int) not a string.
I haven't to break this statement like the following:
data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles'])
data.decode('utf-8').split('\n')
the above statement is what brought an error in my script but the solution is to do it like
data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8').split('\n')
and this now work properly
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I tried to access 'gold_spent` key in some dictionary made from JSON file.
Here is my code:
import json
import requests
response = requests.get("https://sky.shiiyu.moe/api/v2/profile/tProfile")
json_data = json.loads(response.text)
print(json_data['gold_spent'])
When I run this I get this "KeyError: 'gold_spent'"
I don't know what I am doing wrong, any help would be appreciated.
The data you are looking for is nested. See below.
print(json_data['profiles']['590cedda63e145ea98d44015649aba30']['data']['misc']['auctions_buy']['gold_spent'])
output
46294255
You experienced an exception because gold_spent isn't at all a key of first level, you need to investigate the structure to find it. Accessing non-existing key in the dictionary would always end with KeyError exception.
import json
import requests
response = requests.get("https://sky.shiiyu.moe/api/v2/profile/tProfile")
json_data = json.loads(response.text)
print(json_data.keys())
# dict_keys(['profiles'])
print(json_data['profiles'].keys())
# dict_keys(['590cedda63e145ea98d44015649aba30'])
print(json_data['profiles']['590cedda63e145ea98d44015649aba30'].keys())
# dict_keys(['profile_id', 'cute_name', 'current', 'last_save', 'raw', 'items', 'data'])
print(json_data['profiles']['590cedda63e145ea98d44015649aba30']['data']['misc']['auctions_buy']['gold_spent'])
# 46294255
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So I am trying to get into python, and am using other examples that I find online to understand certain functions better.
I found a post online that shared a way to check prices on an item through CamelCamelCamel.
They had it set to request from a specific url, so I decided to change it to userinput instead.
How can I just simply loop this function?
It runs fine afaik once, but after the inital process i get 'Process finished with exit code 0', which isn't necessarily a problem.
For the script to perform how I would like it to. It would be nice if there was a break from maybe, 'quit' or something, but after it processes the URL that was given, I would like it to request for a new URL.
Im sure theres a way to check for a specific url, IE this should only work for Camelcamelcamel, so to limit to only that domain.
Im more familiar with Batch, and have kinda gotten away with using batch to run my python files to circumvent what I dont understand.
Personally if I could . . .
I would just mark the funct as 'top:'
and put goto top at the bottom of the script.
from bs4 import BeautifulSoup
import requests
print("Enter CamelCamelCamel Link: ")
plink = input("")
headers = {'User-Agent': 'Mozilla/5.0'}
r = requests.get(plink,headers=headers)
data = r.text
soup = BeautifulSoup(data,'html.parser')
table_data = soup.select('table.product_pane tbody tr td')
hprice = table_data[1].string
hdate = table_data[2].string
lprice = table_data[7].string
ldate = table_data[8].string
print ('High price-',hprice)
print ("[H-Date]", hdate)
print ('---------------')
print ('Low price-',lprice)
print ("[L-Date]", ldate)
Also how could I find the difference from the date I obtain from either hdate or ldate, from today/now. How the dates I parsed they're strings and I got. TypeError: unsupported operand type(s) for +=: 'int' and 'str'.
This is really just for learning, any example works, It doesnt have to be that site in specific.
In Python, you have access to several different types of looping control structures, including:
while statements
while (condition) # Will execute until condition is no longer True (or until break is called)
<statements to execute while looping>
for statements
for i in range(10) # Will execute 10 times (or until break is called)
<statements to execute while looping>
Each one has its strengths and weaknesses, and the documentation at Python.org is very thorough but easy to assimilate.
https://docs.python.org/3/tutorial/controlflow.html
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm currently trying to populate a SQL database (for an assignment) through Python. I have created a function to help me do that.
When I run the function, however, I receive a 'List index out of range" Index error. I would appreciate all and any help!
I have tried reverting to some old code, but it doesn't help with the current problem.
As I understand that there is apparently no "field[1]" (otherwise I wouldn't be receiving this error) I have tried printing each step of my function as it occurs... only to discover that I can, in fact, print the elusive value, but still receive an error about that line?
I have included all the code I believe to be relevant, however, if you think I must be missing something, feel free to contact me. Thank you very much!
def populateStudentTable(textFile,targetTable):
connection = sqlite3.connect(dbName)
cursor = connection.cursor()
numRecs = 0
dataRecs = []
textRec = textFile.readline()
while textRec != "":
numRecs += 1
field = textRec.split(", ")
print(field)
print(field[0])
print(field[1])
textRec = textFile.readline()
When I run the program, it prints the second item in the list: field[1]
But then after that, it gives me an error...
['VENNGEOR', 'Georgia', 'Venna', '12', 'Maths', '8596746234']
VENNGEOR
Georgia
This is the error I receive:
Traceback (most recent call last):
File "h:\Digital Solutions\VS Code\Dev.py", line 22, in <module>
numRecs = populateStudentTable(textFile,"tblMentor")
File "h:\Digital Solutions\VS Code\Dev.py", line 14, in
populateStudentTable:print(field[1])
IndexError: list index out of range
After reading some comments and doing some more debugging of my own, I discovered that "buran" was correct. I had simply left some empty lines and was trying to run a loop on an empty line.
One line in textFile did not contain the number of , characters you expect. When you do field = textRec.split(", ") then resulting field might not have 3 elements as you expect if there was less than two , in the line.
Examine the content of your file or simply instead of printing elements of field print field itself. This will make it easier for you to understand where you got this wrong.
Also note you are splitting by ", " (not ","), so be aware of situations like this may also result in your error:
>>> foo = "a,b,c, d"
>>> foo.split(", ")
['a,b,c', 'd']
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am parsing a huge JSON in python, i am parsing it step by step, i am stuck at a point and i can't figure out why the code is not running properly, my code is;
I want to get value of all the WHO_REGION for all the attr in an array, as i am not an expert in python programming..... here is the JSON, "http://apps.who.int/gho/athena/data/COUNTRY.json"
import json
from pprint import pprint
mylabel = []
mylabel2 = []
with open('C:\Users\Syed Saad Ahmed\Desktop\FL\COUNTRY.json') as data_file:
data = json.load(data_file)
for i in range(0,246):
mylabel.append(data["dimension"][0]["code"][i]["label"])
print mylabel
for j in range(0,246):
for k in range(0,21):
if(data["dimension"][0]["code"][j]["attr"][k]["category"]=='WHO_REGION'):
mylabel2.append(data["dimension"][0]["code"][j]["attr"][k]["value"])
print mylabel2
You can browse your JSON object using nested loops:
import json
obj = json.loads(data)
dimention_list = obj["dimension"]
for dimension in dimention_list:
code_list = dimension["code"]
for code in code_list:
attr_list = code["attr"]
for attr in attr_list:
if attr["category"] == "WHO_REGION":
print(attr["value"])
It is complex because each entry contains a list of something…
Of course, it's up to you to add some filtering.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to store some kind of persistent tracking to my application. Like for example ,
application.py supports 3 arguments, --firstarg --secondarg --thirdarg.
user can execute application.py using either one of the argument. I want to provide a feature where in user can track that he has already completed running the firstarg. In order to achieve this, i wanted to store a file called status.log, where the tracker will be stored.
Initially, status.log has
firstarg : 0
secondarg : 0
thirdarg : 0
once the user executes the first arg, it should turn the line , firstarg : 1
so when users wants, he can check if he has already completed running the firstarg or not.
Is it possible ?
I tried shelve, its not working for me for some reason. I am not seeing any logs written to the file.
Thanks.
I'd say use a JSON file as a persistent store and use the load and dump methods for reads and writes.
The JSON method is built in so all you need is to import it and use it:
import json
data_file = '/path/to/file'
# Load current state from file
contents = json.load(data_file)
# Do something
# ....
# ....
# Change values
contents['firstarg'] = firstarg
# Save to file
json.dump(contents, data_file)
Since you don't have a code sample, this is a simple approach