I was working on a python program made to write out the IP addresses from an error log file. I got it coded but whenever I try it on my error log I get a
TypeError: 'NoneType' object is not subscriptable
I wrote the code under this in case anyone wants to see what I did specifically. If anyone knows my mistake that would be great.
import re
with open(r'C:\Users\Admin\Desktop/Test error file.txt') as fh:
file = fh.readlines()
pattern = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
list=[]
for line in file:
lst.append(pattern.search(line)[0])
print(list)
pattern.search returns None if no match is found. To account for this try
for line in file:
match = pattern.search(line)
if match is not None:
lst.append(match[0])
else:
lst.append(None)
Here I appended a None value if there was no match. You can change the logic to do what you need if there is no match.
Very new to python, I'm trying to take in a command line argument which is a website and set it to a variable. I use the line below to do this.
sitefile = ur.urlopen(sys.argv[1])
The problem is it only works when formatted perfectly in the command line as 'python filename.py http://mywebsite.com/contacts.html'. I want to be able to drop the http://. I've tried the following 2 ways:
sitefile = ur.urlopen(sys.argv[1].startswith('http://'))
gets error message: AttributeError: 'bool' object has no attribute 'timeout'
sitefile = 'http://' + (ur.urlopen(sys.argv[1]))
gets error message: ValueError: unknown url type: 'mywebsite.com/contacts.html'. It appears to just ignore the first half of this concat.
What's the ur? give the complete code.
sys.argv[1].startswith('http://') return a bool object, drop the http:// should use sys.argv[1].replace('http://', '').
I think the code should like the following lines:
#!/usr/bin/env python
# encoding: utf-8
import sys
import urllib2
if len(sys.argv) != 2:
print('usage: {} <url>'.format(sys.argv[0]))
sys.exit()
url = sys.argv[1]
req = urllib2.urlopen(url)
print(req.read())
I have a Python script that converts JSON to CSV successfully when run in PyCharm.
When I move that Python script into a Python Transformer in MuleSoft, the script fails with the error:
TypeError: unicode indices must be integers in at line number 10 (javax.script.ScriptException). Message payload is of type: String (org.mule.api.transformer.TransformerMessagingException). Message payload is of type: String
What is the difference between Python and Jython in this context? I don't get it!
Here is the Python:
import csv
import io
data = message.getInvocationProperty("my_JSON")
output = io.BytesIO()
writer = csv.writer(output)
for item in data:
writer.writerow(([item['observationid'], item['fkey_observation'], item['value'], item['participantid'], item['uom'], item['finishtime'], item['starttime'], item['observedproperty'], item['measuretime'], item['measurementid'], item['longitude'], item['identifier'], item['latitude']]))
result = output.getvalue()
"my_JSON" is a variable containing the JSON.
You seem to have forgotten to parse the JSON, like so: data = json.loads(data).
Without that, data is a str, item is a str of length 1, and item['observationid'] raises TypeError.
I have a simple python script that i wrote for IDA, but i'am can't figure out what am i doing wrong.
file = open("c:\\example.txt", "r")
for line in file:
if line == "":
pass
else:
addr = line.split(None,1)
if len(addr) < 2:
pass
else:
address = ''.join(addr[0])
if(idc.Jump(address)):
sea = ScreenEA()
else:
print "There is a problem with the destenation address"
counter = 0
for l in addr[1]:
PatchByte(sea+counter, ord(l))
counter += 1
file.close()
Tow lines from example.txt file:
0x1001b3a4 Kernel32.DLL
0x1001b3c8 CreateToolhelp32Snapshot
The error message i get is:
obvious to me the error is at if(idc.Jump(address)): line, and i have tried to call that with if(Jump(addr[0])): but i am getting the same error message.
I saw the Jump function at the official doc, but it seems like i am passing the right argument to it.
What could be the problem?
I think the problem is that you are passing a string to Jump(). Accordingly to the docs it has to be a long.
This question already has answers here:
How can I parse (read) and use JSON?
(5 answers)
Closed 29 days ago.
In Python I'm getting an error:
Exception: (<type 'exceptions.AttributeError'>,
AttributeError("'str' object has no attribute 'read'",), <traceback object at 0x1543ab8>)
Given python code:
def getEntries (self, sub):
url = 'http://www.reddit.com/'
if (sub != ''):
url += 'r/' + sub
request = urllib2.Request (url +
'.json', None, {'User-Agent' : 'Reddit desktop client by /user/RobinJ1995/'})
response = urllib2.urlopen (request)
jsonStr = response.read()
return json.load(jsonStr)['data']['children']
What does this error mean and what did I do to cause it?
The problem is that for json.load you should pass a file like object with a read function defined. So either you use json.load(response) or json.loads(response.read()).
Ok, this is an old thread but.
I had a same issue, my problem was I used json.load instead of json.loads
This way, json has no problem with loading any kind of dictionary.
Official documentation
json.load - Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.
json.loads - Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.
You need to open the file first. This doesn't work:
json_file = json.load('test.json')
But this works:
f = open('test.json')
json_file = json.load(f)
If you get a python error like this:
AttributeError: 'str' object has no attribute 'some_method'
You probably poisoned your object accidentally by overwriting your object with a string.
How to reproduce this error in python with a few lines of code:
#!/usr/bin/env python
import json
def foobar(json):
msg = json.loads(json)
foobar('{"batman": "yes"}')
Run it, which prints:
AttributeError: 'str' object has no attribute 'loads'
But change the name of the variablename, and it works fine:
#!/usr/bin/env python
import json
def foobar(jsonstring):
msg = json.loads(jsonstring)
foobar('{"batman": "yes"}')
This error is caused when you tried to run a method within a string. String has a few methods, but not the one you are invoking. So stop trying to invoke a method which String does not define and start looking for where you poisoned your object.
AttributeError("'str' object has no attribute 'read'",)
This means exactly what it says: something tried to find a .read attribute on the object that you gave it, and you gave it an object of type str (i.e., you gave it a string).
The error occurred here:
json.load(jsonStr)['data']['children']
Well, you aren't looking for read anywhere, so it must happen in the json.load function that you called (as indicated by the full traceback). That is because json.load is trying to .read the thing that you gave it, but you gave it jsonStr, which currently names a string (which you created by calling .read on the response).
Solution: don't call .read yourself; the function will do this, and is expecting you to give it the response directly so that it can do so.
You could also have figured this out by reading the built-in Python documentation for the function (try help(json.load), or for the entire module (try help(json)), or by checking the documentation for those functions on http://docs.python.org .
Instead of json.load() use json.loads() and it would work:
ex:
import json
from json import dumps
strinjJson = '{"event_type": "affected_element_added"}'
data = json.loads(strinjJson)
print(data)
So, don't use json.load(data.read()) use json.loads(data.read()):
def findMailOfDev(fileName):
file=open(fileName,'r')
data=file.read();
data=json.loads(data)
return data['mail']
use json.loads() function , put the s after that ... just a mistake btw i just realized after i searched error
def getEntries (self, sub):
url = 'http://www.reddit.com/'
if (sub != ''):
url += 'r/' + sub
request = urllib2.Request (url +
'.json', None, {'User-Agent' : 'Reddit desktop client by /user/RobinJ1995/'})
response = urllib2.urlopen (request)
jsonStr = response.read()
return json.loads(jsonStr)['data']['children']
try this
Open the file as a text file first
json_data = open("data.json", "r")
Now load it to dict
dict_data = json.load(json_data)
If you need to convert string to json. Then use loads() method instead of load(). load() function uses to load data from a file so used loads() to convert string to json object.
j_obj = json.loads('["label" : "data"]')