I wish to do some kind of reflection thing where given a line number and a module, I get back the name of the function in that module containing that line. Is this possible in Python?
There is no built-in way to do this in python. However, you could define a function to do something like that, but it would handle modules as files in your current directory:
import re
def get_function_name(module, line):
module_file = module.replace('.', '/') + '.py'
lines = open(module_file, 'r').xreadlines()
i = line - 1
try:
while i:
tmp = next(lines)
i -= 1
except StopIteration:
raise EOFError('Not enought lines in module %s' % module)
function_line = next(lines)
function_name = re.match('def (\w+)\([^)]*\):', function_line)
if function_name:
return function_name.group(1)
raise ValueError('No function declared on line %s' % line)
This function is opening the module passed as a file, iterating until reached the passed line, and then, searching the name of the function using regular expressions. If there was no function declared on the passed line or the line passed exceeded the number of lines of the file, it will raise an Error. E.g.:
>>> get_function_name('my_module.my_submodule', 24)
'my_function_name'
>>> get_function_name('my_module.my_submodule', 25)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 15, in get_function_name
ValueError: No function declared on line 17
>>> get_function_name('my_module.my_submodule', 123456)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in get_function_name
EOFError: Not enought lines in module
Related
I want to create multiple databases but I don't know how I can make it
this is python code:
# 1 - for import data in listbox
def clear_item_list():
items.delete(0, END)
# 2 - for import data in listbox
def fill_item_list(items):
for item_ in items:
items.insert(END, item_)
# 3 - for import data in listbox
def item_list_view():
clear_item_list()
items = app.data_1.view()
fill_item_list(items)
# and that for placement data in entries
def get_selected_row_item(event):
global selected_item
if len(items.curselection()) > 0:
index = items.curselection()[0]
selected_item = items.get(index)[:]
item_name.delete(0, END)
item_name.insert(END, selected_item[1])
item_price.delete(0, END)
item_price.insert(END, selected_item[2])
items.bind("<<ListboxSelect>>", get_selected_row_item)
This code is for making a table:
"CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY , Namee VARCHAR , price INTEGER )"
I don't have any idea this is my problem or not, because when I wanna use price, type that data is string and python raise this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Green\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "D:\python\WindowsProject\app\manager\manager_sign_in.py", line 44, in back_to_main_manager
main_screen()
NameError: name 'main_screen' is not defined
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Green\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "D:\python\WindowsProject\app\manager\sign.py", line 33, in back_to_main_mngr
main_screen()
NameError: name 'main_screen' is not defined
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Green\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "D:\python\WindowsProject\app\main.py", line 33, in user_sign
user_screen()
NameError: name 'user_screen' is not defined
Traceback (most recent call last):
File "D:\python\WindowsProject\app\main.py", line 4, in <module>
from app.user.user_sign_in import *
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 240, in <module>
user_screen()
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 236, in user_screen
item_list_view()
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 55, in item_list_view
fill_item_list(items)
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 48, in fill_item_list
items.insert(END, item_)
TypeError: 'str' object cannot be interpreted as an integer
and this is input data:
(1, 'pizza', '6')
if you can help me pls say to I give you more data about that if you need
The issue is on the below function:
def fill_item_list(items): # <- items is passed argument
for item_ in items:
# "items" below is expected to be an instance of tkinter Listbox
# but it is actually the passed argument (a list object)
items.insert(END, item_)
You used same name on the passed argument as the tkinter Listbox.
Use another name for the passed argument:
def fill_item_list(data): # used "data" instead of "items"
for item_ in data:
items.insert(END, item_)
I am making a blockchain, I am storing the latest block in a file named lb.store
,but my code to open and read the file returns ''.
Here is the Error.
Traceback (most recent call last):
File "C:\Users\ShayanNew\Documents\programming\Python\Blockchain\Node\node.py", line 48, in <module>
recieve_request()
File "C:\Users\ShayanNew\Documents\programming\Python\Blockchain\Node\node.py", line 39, in recieve_request
add_block(data)
File "C:\Users\ShayanNew\Documents\programming\Python\Blockchain\Node\node.py", line 7, in add_block
new_block_number = int(lblock_number) + 1
ValueError: invalid literal for int() with base 10: ''
Here is the full code that caused this:
lblock_numberf = open("lb.store","a+")
lblock_number = lblock_numberf.read()
lblock_numberf.close()
new_block_number = int(lblock_number) + 1
It looks like that the file you're trying to read is either empty or the end of the string appears to be <"">. Play around the values to debug the problem
edited..
full traceback:
Traceback (most recent call last):
File "dscli.py", line 36, in <module>
main()
File "dscli.py", line 31, in main
instance_StreamingDownloader.download_all()
File "file.py", line 283, in download_all
time_first_frame_last_segment = self.get_time_saved_segment(crrt_segment - 1)
File "file.py", line 239, in get_time_saved_segment
return(start_time)
UnboundLocalError: local variable 'start_time' referenced before assignment
code here
It gets only first segment and then error.
How can I solve this issue?
code from github
the answer is quite simple -
the condition allows some case when start_time is not defined during script run
so as it is not defined - it fails
start_time is defined inside an if statement that's inside a for loop.
What if you don't enter the loop, or the condition isn't met? What should the function return?
start_time needs to be initialized (eg start_time = 0 / None / False) in the function body, outside any control flow clauses, so that it's always defined, and therefore you can always return it.
when condition isn't met then:
Traceback (most recent call last):
File "dscli.py", line 36, in <module>
main()
File "dscli.py", line 31, in main
instance_StreamingDownloader.download_all()
File "file.py", line 286, in download_all
lenght_ahead_buffered = time_first_frame_last_segment - time_if_streaming + random_perturbation
TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'
line 280-286:
while continue_download:
time_first_frame_last_segment = self.get_time_saved_segment(crrt_segment - 1)
time_if_streaming = time.time() - init_time
random_perturbation = random.gauss(0, self.random_time)
if self.verbose > 1:
print("time in video if streaming: " + str(time_if_streaming))
I am trying to use a file to read ip addresses and then find out corresponding location of that address
import IP2Location;
IP2LocObj = IP2Location.IP2Location();
IP2LocObj.open("data/IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE.BIN");
#t=open('output.txt','w');
t=open('test_ip','r');
Line=t.readline();
While line:
rec = IP2LocObj.get_all(Line);
Line=t.readline();
print rec.country_short
error is coming here
Traceback (most recent call last):
File "myprogram.py", line 8, in <module>
rec = IP2LocObj.get_all(t);
File "/home/networkgroup/Downloads/IP2Location-Python-master/IP2Location.py", line 219, in get_all
return self._get_record(addr)
File "/home/networkgroup/Downloads/IP2Location-Python-master/IP2Location.py", line 364, in _get_record
ipv = self._parse_addr(ip)
File "/home/networkgroup/Downloads/IP2Location-Python-master/IP2Location.py", line 357, in _parse_addr
socket.inet_pton(socket.AF_INET, addr)
TypeError: inet_pton() argument 2 must be string, not file
This code is giving error.You can check out the sample code here http://www.ip2location.com/developers/python
Please try the new Python codes below.
import IP2Location;
IP2LocObj = IP2Location.IP2Location();
IP2LocObj.open("IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE-SAMPLE.BIN"); # This is sample database
with open('test_ip.txt') as f: # file containing ip addresses
for line_terminated in f:
line = line_terminated.rstrip('\r\n'); # strip newline
if line: # non-blank lines
print line
rec = IP2LocObj.get_all(line);
print rec.country_short
I have wrapper function, that takes other function as parameter, catches an exception and does something with it:
def exceptionCatchingWrapper(funcToCall,destForException,*args,**kwargs):
try:
r=funcToCall(*args,**kwargs)
except:
destForException["exc_info"]=sys.exc_info()
else:
return r
I realized that when an exception is caught, the stack trace taken from sys.exc_info() contains only information about exceptionCatchingWrapper() itself and nothing deeper. Is it possible and how to obtain full stack trace after such call?
import traceback
def a(x):
b(x)
def b(x):
x/0
d = {}
exceptionCatchingWrapper(a, d, 10)
Traceback is stored in the dictionary:
>>> traceback.print_tb(d['exc_info'][2]
File "<stdin>", line 3, in exceptionCatchingWrapper
File "<stdin>", line 2, in a
File "<stdin>", line 2, in b
>>> traceback.print_exception(d['exc_info'][0],d['exc_info'][1],d['exc_info'][2])
Traceback (most recent call last):
File "<stdin>", line 3, in exceptionCatchingWrapper
File "<stdin>", line 2, in a
File "<stdin>", line 2, in b
ZeroDivisionError: integer division or modulo by zero
More information in the traceback module documentation.
Not sure if this is what you need but these might be a way you can print the traceback:
import traceback
try:
s += 1 #this doesnt exist yet
except:
a = traceback.format_exc()
print a
-or-
import traceback, sys
def DummyFunc2():
s += 1 #this doesnt exist yet
def DummyFunc1():
DummyFunc2()
try:
DummyFunc1()
except:
_, err, tb = sys.exc_info()
tb_lines = traceback.extract_tb(tb)
for idx, trace in enumerate( traceback.format_list(tb_lines) ):
print "[INDEX %d]\n%s" % (idx,trace)
print err
output:
>>>
[INDEX 0]
File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 9, in <module>
DummyFunc1()
[INDEX 1]
File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 6, in DummyFunc1
DummyFunc2()
[INDEX 2]
File "C:/Python27/Lib/site-packages/xy/printtrace.py", line 4, in DummyFunc2
s += 1 #this doesnt exist yet
local variable 's' referenced before assignment
>>>