Python Trace Tables and ver 2 to ver 3 issue - python

I found this code for printing a program trace and it works fine in Python2.
However, in Python 3 there are issues. I addressed the first one by replacing execfile(file_name) with exec(open(filename).read()), but now there is still an error of KeyError: 'do_setlocale'
I'm out of my depth here - I just want an easy way to trace variables in programs line by line - I like the way this program works and it would be great to get it working with Python 3. I even tried an online conversion program but got the same KeyError: 'do_setlocale'
Can anyone please help me to get it working?
import sys
if len(sys.argv) < 2:
print __doc__
exit()
else:
file_name = sys.argv[1]
past_locals = {}
variable_list = []
table_content = ""
ignored_variables = set([
'file_name',
'trace',
'sys',
'past_locals',
'variable_list',
'table_content',
'getattr',
'name',
'self',
'object',
'consumed',
'data',
'ignored_variables'])
def trace(frame, event, arg_unused):
global past_locals, variable_list, table_content, ignored_variables
relevant_locals = {}
all_locals = frame.f_locals.copy()
for k,v in all_locals.items():
if not k.startswith("__") and k not in ignored_variables:
relevant_locals[k] = v
if len(relevant_locals) > 0 and past_locals != relevant_locals:
for i in relevant_locals:
if i not in past_locals:
variable_list.append(i)
table_content += str(frame.f_lineno) + " || "
for variable in variable_list:
table_content += str(relevant_locals[variable]) + " | "
table_content = table_content[:-2]
table_content += '\n'
past_locals = relevant_locals
return trace
sys.settrace(trace)
execfile(file_name)
table_header = "L || "
for variable in variable_list:
table_header += variable + ' | '
table_header = table_header[:-2]
print table_header
print table_content
# python traceTable.py problem1.py
# problem1.py
a = 1
b = 2
a = a + b

That program has a couple of major flaws – for example, if the program being traced includes any functions with local variables, it will crash, even in Python 2.
Therefore, since I have nothing better to do, I wrote a program to do something like this called pytrace. It's written for Python 3.6, although it probably wouldn't take too long to make it work on lower versions if you need to.
Its output is a little different to your program's, but not massively so – the only thing that's missing is line numbers, which I imagine you could add in fairly easily (print frame.f_lineno at appropriate points). The rest is purely how the data are presented (your program stores all the output until the end so it can work out table headers, whereas mine prints everything as it goes).

Related

invalid syntax error : Quine McCluskey Algorithm in python

i'm totally new in python, and here is some code my friend sent it for me, this is Quine-McCluskey Algorithm that provides answer with getting minterms, the code is somehow simple but because i am not exprienced python programmer i have not much ideas for fixing this problem
this is the source code : Quine-McCluskey (github)
def find_minimum_cost(Chart, unchecked):
P_final = []
#essential_prime = list with terms with only one 1 (Essential Prime Implicants)
essential_prime = find_prime(Chart)
essential_prime = remove_redundant_list(essential_prime)
#print out the essential primes
if len(essential_prime)>0:
s = "\nEssential Prime Implicants :\n"
for i in range(len(unchecked)):
for j in essential_prime:
if j == i:
s= s+binary_to_letter(unchecked[i])+' , '
print s[:(len(s)-3)] #ERROR <--------
#modifiy the chart to exclude the covered terms
for i in range(len(essential_prime)):
for col in range(len(Chart[0])):
if Chart[essential_prime[i]][col] == 1:
for row in range(len(Chart)):
Chart[row][col] = 0
-
File "C:\Users\Lenovo\Desktop\main.py", line 204
print s[:(len(s)-3)]
^
SyntaxError: invalid syntax
the Error is in this line : print s[:(len(s)-3)]
The original author intended for the program to be executed with a python2 interpreter.
He wrote (roughly):
print s
To execute with a modern python3 interpreter, you would instead need:
print(s)

check if PIE is enable in python

Here since yesterday I look at how to detect if the protection "PIE" is activated. For that I analyzed the output of the relocation entries to see if _ITM_deregisterTMClone is present or not. Is there a better way to detect PIE without going through a readelf output?
Here is what I currently have :
def display_pie(counter):
if (counter == 1):
print("Pie : Enable")
else:
print("Pie: No PIE")
def check_file_pie(data_file):
data = []
data2 = []
result = []
ctn = 0
check = subprocess.Popen(["readelf", "-r", data_file],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = check.stdout.readlines()
for x in result:
data.append(list(x))
for lines in data:
data2.append("".join(map(chr, lines)))
for new_lines in data2:
if "_ITM_deregisterTMClone" in new_lines:
ctn += 1
display_pie(ctn)
Thank you it's quite technical so if someone can explain me a better way to check the Executable Independent Position, I'm interested!
You can use pyelftools to check if the ELF is a shared object and if the image base address is zero:
def is_pie(filename):
from elftools.elf.elffile import ELFFile
with open(filename, 'rb') as file:
elffile = ELFFile(file)
base_address = next(seg for seg in elffile.iter_segments() if seg['p_type'] == "PT_LOAD")['p_vaddr']
return elffile.elftype == 'DYN' and base_address == 0
You can use pwntools, which has functionality for manipulating ELF files. Example usage:
>>> from pwn import *
>>> e = ELF('your-elf-file')
>>> e.pie
True
If you want to know how it is implemented, you can find the source code here.

Why would Python's sys.stdout.write() not work after I index a list obtained from a file object using os.popen?

Updated Updated Question:
I have a JQuery $.ajax call that looks like this:
$.ajax({
url: 'http://website.domain.gov/cgi-bin/myFolder/script.py',
type: 'post',
dataType: 'json',
data:{'lat':'30.5', 'lon':'-80.2'},
success: function(response){alert(response.data.lat);
otherFunction();}
});
In script.py, which runs with no errors on its own, I do the following:
#!/usr/bin/python
import sys, json, cgi
import os
fs = cgi.FieldStorage()
d = {}
for k in fs.keys():
d[k] = fs.getvalue(k)
ilat = d['lat']
ilon = d['lon']
pntstr = ilat + ',' + ilon
my_list = []
#os.chdir('..'); os.chdir('..')
#os.chdir('a_place/where_data/exists')
# If you'd like to run this code, you probably don't have grib files or 'degrib', so another unix command will have to be utilized to open some sort of dummy data
f = os.popen('degrib '+'datafilename '+
'options '+ pntstr)
out = f.read()
# data has 5 columns, many rows
j = 0
while j < (5*num_lines_to_read):
my_list.append(out[j+4])
j += 5
f.close()
#os.chdir('..') etc until I get back to /cgi-bin/myFolder directory...
x = my_list[0]
result = {}
result['data'] = d
sys.stdout.write('Content-Type: application/json\n\n')
sys.stdout.write(json.dumps(result))
sys.stdout.close()
NOTE: 'd' is the dummy value and has nothing to do with 'my_list'...for now
When I update the web page I'm developing and try to return 'd' from Python (in the form of an alert), I get a "very helpful" server 500 error.
I've narrowed the problem down to the "x = my_list[0]" line. If I instead type "x = my_list", I get no error. sys.stdout.write() only stops working when I try to index "my_list". I tried printing the list. It's not empty and contains the expected values with expected types. I get successful output from sys.stdout.write() if I place it before "x = my_list[0]". Problem is, I'll eventually use "my_list" to create the output that is written to stdout.
Is there some obscure file I/O thing that I'm missing here?
The expression my_list[0] is throwing an exception. Either it isn't a list, or whatever it is doesn't support the array operator.
Try examining your web server log files. Try printing type(my_list) and len(my_list) after you emit the content-type header.

input-validation & string conversion

I have a script, which take input from the user and I want to validate the input first then convert the user-input to a predefined format. The input should be like this:
my_script -c 'formatDate(%d/%m) == 23/5 && userName == John Dee && status == c
At the moment I'm dealing with formatDate() bit only. The main rules are:
The format string for year,month,day can come in any order
if m [or y or d] is missing that will be added using current_month; same for others
the same delimiter must be used for the format strings and the values
the keys and values must be separated by ==
the different constraint must be separated by &&
single or multiple constraints are allowed
So, for the given example, it should return 20110523 as a valid constraint. After a bit of work, this is what I come up with, which is pretty much working:
#!/usr/bin/env python
#
import sys, re
from time import localtime, strftime
theDy = strftime('%d', localtime())
theMn = strftime('%m', localtime())
theYr = strftime('%Y', localtime())
def main(arg):
print "input string: %s" % arg
arg = "".join(arg.split()).lower()
if arg.startswith('=') or re.search('===', arg) or "==" not in arg:
sys.exit("Invalid query string!")
else: my_arg = arg.split('&&')
c_dict = {}
for ix in range(len(my_arg)):
LL = my_arg[ix].split('==')
#LL = dict(zip(LL[:-1:2], LL[1::2]))
# don't add duplicate key
if not c_dict.has_key(LL[0]):
c_dict[LL[0]] = LL[1]
for k,v in sorted(c_dict.items()):
if k.startswith('formatdate') :
ymd = re.sub(r'[(,)]', ' ', k).replace('formatdate','')
ymd = (str(ymd).strip()).split('/')
if len(ymd) <= 3 and len(ymd) == len(v.split('/')):
d_dict = dict(zip(ymd, v.split('/')))
if not d_dict.has_key('%y'):
d_dict['%y'] = theYr
if not d_dict.has_key('%m'):
d_dict['%m'] = theMn
if not d_dict.has_key('%d'):
d_dict['%d'] = theDy
else: sys.exit('date format mismatched!!')
Y = d_dict['%y'];
if d_dict['%m'].isdigit() and int(d_dict['%m']) <=12:
M = d_dict['%m'].zfill(2)
else: sys.exit("\"Month\" is not numeric or out of range.\nExiting...\n")
if d_dict['%d'].isdigit() and int(d_dict['%d']) <=31:
D = d_dict['%d'].zfill(2)
else: sys.exit("\"Day\" is not numeric or out of range.\nExiting...\n")
# next line needed for future use
fmtFile = re.compile('%s%s%s' % (Y,M,D))
print "file_name is: %s" % Y+M+D
if __name__ == "__main__":
main('formatDate(%d/%m)== 23/5')
My questions are:
Am I making it unnecessarily complected or expensive? Is there any easier way?
How to identify which "delimiter" user has used [as opposed to using a fixed one]?
Thanks for your time. Cheers!!
You're not making a complication, but have you thought of the consequences of expanding the grammar of the user requests?
The simplest parser is Shunting yard algorithm. You can adopt it to the user requests and expand the grammar easily. You can find Python implementation here.

printSoln module problem

Hi I found in book:Numerical Methods in engineering with Python the module run_kut5, but for that module I need module printSoln, all provided in the book. Now I cp the code, made necessary line adjustments and so. The code looks like:
# -*- coding: cp1250 -*-
## module printSoln
''' printSoln(X,Y,freq).
Prints X and Y returned from the differential
equation solvers using printput frequency ’freq’.
freq = n prints every nth step.
freq = 0 prints initial and final values only.
'''
def printSoln(X,Y,freq):
def printHead(n):
print "\n x ",
for i in range (n):
print " y[",i,"] ",
print
def printLine(x,y,n):
print "%13.4e"% x,f
for i in range (n):
print "%13.4e"% y[i],
print
m = len(Y)
try: n = len(Y[0])
except TypeError: n = 1
if freq == 0: freq = m
printHead(n)
for i in range(0,m,freq):
printLine(X[i],Y[i],n)
if i != m - 1: printLine(X[m - 1],Y[m - 1],n)
Now, when I run the program it says:
line 24, in <module>
m = len(Y)
NameError: name 'Y' is not defined
But I cp'd from the book :\ So now when I call the run_kut module I get the same error, no Y defined in printSoln...
I'm trying to figure this out but I suck :(
Help, please...
I would guess it's a tabs/spaces problem - check that you don't have mixed tabs and spaces in the indentation.
EDIT: If it's not indentation, and since your error message contains "<module>" and not a filename, I'm guessing you're pasting this into an interactive interpreter.
Instead, you should paste the code into a file called printsoln.py, and then run this in the interactive interpreter:
from printsoln import printSoln
If you still want to paste it all in the interpreter then you'll probably need to remove the blank lines - those after def printSoln and after each internal function. The interactive interpreter uses blank lines to figure out when you're done with a multi-line definition, and tries to evaluate m = len(Y) outside the context of function printSoln. In this context, variable Y doesn't exist.

Categories

Resources