I have following code
import sys
from ctypes import *
from ctypes.util import find_library
libc = cdll.LoadLibrary(find_library("c"))
CTL_KERN = 1
KERN_SHMMAX = 34
sysctl_names = {
'memory_shared_buffers' : (CTL_KERN, KERN_SHMMAX),
}
def posix_sysctl_long(name):
_mem = c_uint64(0)
_arr = c_int * 2
_name = _arr()
_name[0] = c_int(sysctl_names[name][0])
_name[1] = c_int(sysctl_names[name][1])
result = libc.sysctl(_name, byref(_mem), c_size_t(sizeof(_mem)), None, c_size_t(0))
if result != 0:
raise Exception('sysctl returned with error %s' % result)
return _mem.value
print posix_sysctl_long('memory_shared_buffers')
which produces following result:
Traceback (most recent call last):
File "test.py", line 23, in <module>
print posix_sysctl_long('memory_shared_buffers')
File "test.py", line 20, in posix_sysctl_long
raise Exception('sysctl returned with error %s' % result)
Exception: sysctl returned with error -1
I gues I did something wrong. What would be the correct calling convention? How would I find out what exactly went wrong?
You are not providing the correct values to the sysctl function. Detailed information on the arguments of sysctl() can be found here.
Here are your errors:
You have forgotten the nlen argument (second argument)
The oldlenp argument is a pointer to the size, not directly the size
Here is the correct function (with minor improvement):
def posix_sysctl_long(name):
_mem = c_uint64(0)
_def = sysctl_names[name]
_arr = c_int * len(_def)
_name = _arr()
for i, v in enumerate(_def):
_name[i] = c_int(v)
_sz = c_size_t(sizeof(_mem))
result = libc.sysctl(_name, len(_def), byref(_mem), byref(_sz), None, c_size_t(0))
if result != 0:
raise Exception('sysctl returned with error %s' % result)
return _mem.value
Related
I want to print an error's line number and error message in a nicely displayed way. The follow is my code, which uses linecache:
import linecache
def func():
if xx == 1:
print('ok')
try:
func()
except:
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
print_('ERROR - (LINE {} "{}"): {}'.format(lineno, line.strip(), exc_obj))
However, this only gives where the func() is called:
ERROR - (LINE 8 ""): name 'xx' is not defined
Is there a way to print the line number where the error actually occured, which should be Line 4? Or even better, can I print Line 8 and then trace back to line 4? For example, if I do not use try - except, the code:
def func():
if xx == 1:
print('ok')
func()
will give me the following error message, which is much better to locate the error:
File "<input>", line 5, in <module>
File "<input>", line 2, in func
NameError: name 'xx' is not defined. Did you mean: 'xxx'?
You can use traceback and sys modules to get advanced traceback output like you are wishing for.
Here is an example:
import traceback
import sys
def func():
zeroDivide = 1 / 0
try:
func()
except Exception:
print(traceback.format_exc()) # This line is for getting traceback.
print(sys.exc_info()[2]) # This line is getting for the error type.
Output will be:
Traceback (most recent call last):
File "b:\abc\1234\pppp\main.py", line 10, in <module>
func()
File "b:\abc\1234\pppp\main.py", line 7, in func
zeroDivide = 1 / 0
ZeroDivisionError: division by zero
You can use the traceback module to get the line number of the error,
import traceback
def function():
try:
# code
except:
tb_list = traceback.extract_tb(sys.exc_info()[2])
line_number = tb_list[-1][1]
print("An error occurred on line:", line_number)
You can use the traceback.extract_tb() function. This function returns a list of traceback objects, each of which contain information about the stack trace. The last element of this list, tb_list[-1], holds information about the line where the exception occurred. To access the line number, you can use the second element of this tuple, tb_list[-1][1]. This value can then be printed using the print() function.
To get the line number as an int you can get the traceback as a list from traceback.extract_tb(). Looking at the last item gives you the line where the exception was raised:
#soPrintLineOfError2
import sys
import traceback
def func():
if xx == 1:
print('ok')
try:
func()
except Exception as e:
tb = sys.exc_info()[2]
ss = traceback.extract_tb(tb)
ss1 = ss[-1]
print(ss1.line)
print(ss1.lineno)
Output:
if xx == 1:
6
lambda from getattr getting called with "connection" as a keyword argument? Am I misusing the code or is there a bug?
Code and traceback: https://github.com/bigcommerce/bigcommerce-api-python/issues/32
#!/usr/bin/env python2
import bigcommerce
import bigcommerce.api
BIG_URL = 'store-45eg5.mybigcommerce.com'
BIG_USER = 'henry'
BIG_KEY = '10f0f4f371f7953c4d7d7809b62463281f15c829'
api = bigcommerce.api.BigcommerceApi(host=BIG_URL, basic_auth=(BIG_USER, BIG_KEY))
def get_category_id(name):
get_request = api.Categories.get(name)
try:
cat_list = api.Categories.all(name=name)
if cat_list:
return cat_list[0]['id']
else:
return None
except:
return None
def create_category(name):
rp = api.Categories.create(name)
if rp.status == 201:
return rp.json()['id']
else:
return get_category_id(name)
create_category('anothertestingcat')
Gives this traceback:
Traceback (most recent call last):
File "./bigcommerceimporter.py", line 50, in
create_category('anothertestingcat')
File "./bigcommerceimporter.py", line 44, in create_category
rp = api.Categories.create(name)
File "/home/henry/big_test_zone/local/lib/python2.7/site-packages/bigcommerce/api.py", line 57, in
return lambda args, *kwargs: (getattr(self.resource_class, item))(args, connection=self.connection, *kwargs)
TypeError: create() got multiple values for keyword argument 'connection'
Line in api.py that the traceback refers to: https://github.com/bigcommerce/bigcommerce-api-python/blob/master/bigcommerce/api.py#L57
According to the examples, create should be used like this:
api.Categories.create(name = 'anothertestingcat')
Note: You should generate a new API KEY, since you published the current one in this question.
I have searched online for many answers related to TypeError and scanned through my code multiple times but I can't seem to see what is the 3rd argument I'm missing. I am using Python 2.7 with Simpy 3
My code is as follows:
import simpy
import random
RANDOM_SEED = 42
NUM_SERVERS = 1
MTBF = 10
MTTR = 5
TOTAL_ENGINES = 6
TOTAL_SPARES = 3
TOTAL_IN_USE = TOTAL_ENGINES - TOTAL_SPARES
SIM_TIME = 100
class Working(object):
def __init__ (self, env, num, repair_facility, spares_inventory, downtime):
self.env = env
self.repair_facility = repair_facility
self.spares_inventory = spares_inventory
self.downtime = downtime
self.name = 'Engine %d' % (num + 1)
print('%s at %.2f' % (self.name, self.env.now))
self.env.process(self.run())
def run(self):
yield self.env.timeout(random.expovariate(1.0 / MTBF))
print('%s at %.2f' % (self.name, self.env.now))
downtime_start = self.env.now
spare = yield self.spares_inventory.get()
self.downtime.append(self.env.now - downtime_start)
print('%s at %.2f' % (spare.name, self.env.now))
print('%d' % len(spares_inventory.items))
with self.repair_facility.request() as req:
yield req
print('%s begins repair at %.2f' % (self.name, self.env.now))
yield self.env.timeout(random.expovariate(1.0 / MTTR))
yield self.spares_inventory.put(self)
print('%s at %.2f' % (self.name, self.env.now))
print('%d' % len(spares_inventory.items))
def main():
env = simpy.Environment()
repair_facility = simpy.Resource(env, capacity = NUM_SERVERS)
spares_inventory = simpy.Container(env, capacity = TOTAL_ENGINES, init = TOTAL_SPARES)
downtime = []
working = [Working(env, i, repair_facility, spares_inventory, downtime) for i in range(TOTAL_IN_USE)]
env.run(SIM_TIME)
if __name__ == '__main__':
main()
This is the error I keep getting:
Traceback (most recent call last):
File "", line 61, in <module>
main()
File "", line 55, in main
env.run(SIM_TIME)
File "", line 120, in run
self.step()
File "", line 213, in step
raise event._value
TypeError: __init__() takes exactly 3 arguments (2 given)
Any help at all is much appreciated, Thanks a lot in advance
You forgot some extra info in your traceback; above your quoted traceback, there's a a few lines that say:
Traceback (most recent call last):
File "/data/evertr/sw/lib/python2.7/site-packages/simpy/events.py", line 312, in _resume
event = self._generator.send(event._value)
File "simptest.py", line 31, in run
spare = yield self.spares_inventory.get()
TypeError: __init__() takes exactly 3 arguments (2 given)
The above exception was the direct cause of the following exception:
followed by your traceback.
With that, you can see that the self.spares_inventory.get() call is the real culprit. Annoyingly enough, this method is actually a hidden class instantiation (lots of tricky stuff happening behind the scenes in simpy, I've noticed), and that's why you see the __init__() warning.
Basically, you need to supply an amount to self.spares_inventory.get() (there's, for better or worse, no convenient default of 1).
So changing that to
spare = yield self.spares_inventory.get(1)
may solve your problem.
(You'll run into other errors after that though; you'll find out. Those new errors follow the same structure: a traceback, followed by the line The above exception was the direct cause of the following exception, followed by another (less relevant) traceback).
from __future__ import division
import urllib,urllib2
import urllib
import json
from math import log
def hits(word1,word2=""):
query = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s"
if word2 == "":
results = urllib.urlopen(query % word1)
else:
results = urllib.urlopen(query % word1+" "+"AROUND(10)"+" "+word2)
json_res = json.loads(results.read())
google_hits=int(json_res['responseData']['cursor']['estimatedResultCount'])
return google_hits
def so(phrase):
num = hits(phrase,"excellent") * hits("poor")
den = hits(phrase,"poor") * hits("excellent")
ratio = num / den
sop = log(ratio,2)
return sop
print so("beautiful product")
I require the above code to calculate the semantic orientation of a given phrase(or string).
When I execute the code, I get the following error:
Traceback (most recent call last):
File "C:\Python27\nltkexp\ddddd.py", line 32, in <module>
print so("beautiful product")
File "C:\Python27\nltkexp\ddddd.py", line 24, in so
den = hits(phrase,"poor") * hits("excellent")
File "C:\Python27\nltkexp\ddddd.py", line 16, in hits
google_hits=int(json_res['responseData']['cursor']['estimatedResultCount'])
TypeError: 'NoneType' object has no attribute '__getitem__'
How to resolve this error? Can someone point out where I am going wrong with the code?
You are accessing json_res['responseData']['cursor']['estimatedResultCount'], the problem is
json_res or json_res['responseData'] or json_res['responseData']['cursor'] might be None and its can't access key of the NoneType object.
Please print json_resp and check which keys are available in that.
So I am creating a module, and I am importing it to a python shell and running some stuff to make sure all features work and such.
For some reason every time I run the code, it gives the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
#anything can be here
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
So where the #anything can be here is, is whatever is on line 102 of my code. Originally line 102 was:
if isinstance(startindex,datetime.datetime):
and I got the error above. I put a quick print statement on line 102 to check and it gave the same error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
print 'Hello'
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
Is this some sort of bug? Why is it telling me there is an error with datetime on the line print 'Hello'?
Because it may be helpful, I will give you the function I am having trouble with since I have no clue how this is possible. I am keeping the print 'Hello' line so you can see where line 102 is:
def url_maker(latitudes,longitudes,times=None,color='red',label=' ',zoom=12,center=None,start=None,end=None,by=None,size='600x300'):
urls = []
import datetime
if isinstance(times[0],str) or isinstance(times[0],datetime.datetime):
from dateutil import parser
if isinstance(times[0],str):
times = [parser.parse(x) for x in times]
if isinstance(start,str):
startindex = parser.parse(start)
else:
startindex = start
if isinstance(end,str):
endindex = parse.parse(end)
else:
endindex = end
print 'Hello'
if isinstance(startindex,datetime.datetime):
startpos = between_times(times,startindex,by='start')
elif isinstance(startindex,int):
if isinstance(endindex,datetime.datetime):
startpos = between_times(times,endindex,by='end') - start
else:
startpos = start
else:
pass
if isinstance(endindex,datetime.datetime):
endpos = between_times(times,endindex,by='end')
elif isinstance(endindex,int):
if isinstance(startindex,datetime.datetime):
endpos = between_times(times,startindex,by='start') + end
else:
endpos = end
else:
pass
else:
times = range(1,len(latitudes) + 1)
if isinstance(start,int):
startpos = start
else:
startpos = None
if isinstance(end,int):
endpos = end
else:
endpos = None
if isinstance(by,str):
lat,lon,t = latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print lat
t,lats,lons = time_sample(t,by,lat,lon)
elif isinstance(by,int):
lats,lons,t = latitudes[startpos:endpos:by],latitudes[startpos:endpos:by],times[startpos:endpos:by]
else:
lats,lons,t= latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print t
print len(t)
if center == None:
latit = [str(i) for i in lats]
longi = [str(i) for i in lons]
center = '¢er=' + common_finder(latit,longi)
else:
center = '¢er=' + '+'.join(center.split())
zoom = '&zoom=' + str(zoom)
for i in range(len(lats)):
#label = str(i)
x,y = str(lats[i]),str(lons[i])
marker = '&markers=color:' + color + '%7Clabel:' + label + '%7C' + x + ',' + y
url = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&size=' + size + zoom + center + marker + '&sensor=true'
urls.append(url)
#print i
return urls,t
You are running with a stale bytecode cache or are re-running the code in an existing interpreter without restarting it.
The traceback code has only bytecode to work with, which contains filename and linenumber information. When an exception occurs, the source file is loaded to retrieve the original line of code, but if the source file has changed, that leads to the wrong line being shown.
Restart the interpreter and/or remove all *.pyc files; the latter will be recreated when the interpreter imports the code again.
As for your specific exception; you probably imported the datetime class from the datetime module somewhere:
from datetime import datetime
The datetime class does not have a datetime attribute, only the module does.