Given the following input file:
a = 2
b = 3
c = a * b
d = c + 4
I want to run the above input file through a python program that produces
the following output:
a = 2
b = 3
c = a * b = 6
d = c + 4 = 10
The input file is a legal python program, but the output is python with
extra output that prints the value of each variable to the right of the
declaration/assignment. Alternatively, the output could look like:
a = 2
b = 3
c = a * b
c = 6
d = c + 4
d = 10
The motivation for this is to implement a simple "engineer's notebook"
that allows chains of calculations without needing print statements
in the source file.
Here's what I have after modifying D.Shawley's (much appreciated) contribution:
#! /usr/bin/env python
from math import *
import sys
locals = dict()
for line in sys.stdin:
line = line.strip()
if line == '':
continue
saved = locals.copy()
stmt = compile(line,'<stdin>','single')
eval(stmt,None,locals)
print line,
for (k,v) in locals.iteritems():
if k not in saved:
print '=', v,
print
Something like the following is a good start. It's not very Pythonic, but it is pretty close. It doesn't distinguish between newly added variables and modified ones.
#! /usr/bin/env python
import sys
locals = dict()
for line in sys.stdin:
saved = locals.copy()
stmt = compile(line, '<stdin>', 'single')
eval(stmt, None, locals)
print line.strip(),
for (k,v) in locals.iteritems():
if k not in saved:
print '=', v,
print
Related
I have this section of code:
if storagetypecheck1 == "Virtual":
def storagecheck():
d = 1
dforid = str(1-d)
while d <= int(numcount):
storageidprefix = "specimen" + "[" + dforid + "]"
driver.find_element_by_id(storageidprefix + ".storageContainerForSpecimen").click()
pag.press('a')
pag.press('enter')
time.sleep(1)
d = d + 1
storagecheck()
storagecheck()
When the storage type of a webform is set to virtual, it will run and change the type to auto in the textboxes.
The problem is that it has to do so with multiple textboxes which follow the format specimen[x].storageContainerForSpecimen.
However, when I run this code, it just loops over and over without changing the value of d to 2, 3, etc.
I tried having d = 1 above the if statement, but then it says for line dforid = str(1-d) that d is not defined.
Where should I put the d = 1 expression so that it is able to be recognized by the storagecheck() loop while also being able to increase by 1 every loop?
storagecheck() calls itself recursively. Each time it calls itself, the line d = 1 is being executed, so the value of d is being reset. You need to place d outside of the function definition for d to continue incrementing, like so:
if storagetypecheck1 == "Virtual":
d = 1
def storagecheck():
global d
dforid = str(1-d)
while d <= int(numcount):
storageidprefix = "specimen" + "[" + dforid + "]"
driver.find_element_by_id(storageidprefix + ".storageContainerForSpecimen").click()
pag.press('a')
pag.press('enter')
time.sleep(1)
d = d + 1
storagecheck()
storagecheck()
We use the keyword global to introduce the variable d into the namespace of the function.
Lets say I have a text file that looks like:
a
b
start_flag
c
d
e
end_flag
f
g
I wish to iterate over this data line by line, but when I encounter a 'start_flag', I want to iterate until I reach an 'end_flag' and count the number of lines in between:
newline = ''
for line in f:
count = 0
if 'start_flag' in line:
while 'end_flag' not in newline:
count += 1
newline = f.readline()
print(str(count))
What is the expected behavior of this code? Will it iterate like:
a
b
start_flag
c
d
e
end_flag
f
g
Or:
a
b
start_flag
c
d
e
end_flag
c
d
e
end_flag
f
g
There shouldn't be any need to use readline(). Try it like this:
with open(path, 'r') as f:
count = 0
counting = False
for line in f:
if 'start_flag' in line:
counting = True
elif 'end_flag' in line:
counting = False
#do something with your count result
count = 0 #reset it for the next start_flag
if counting is True:
count += 1
This handles it all with the if statements in the correct order, allowing you to just run sequentially through the file in one go. You could obviously add more operations into this, and do things with the results, for example appending them to a list if you expect to run into multiple start and end flags.
Use this:
enter = False
count = 0
for line in f:
if 'start_flag' in line:
enter = True
if 'end_flag' in line:
print count
count = 0
enter = False
if enter is True:
count+=1
I am writing very simple code which takes input from stdin and prints output to stdout.
Input :
4
3
Output(I am getting) :
1None
1.333None
Expected Output :
1
1.333
Can you help me out. Thanks in advance
Here is the code :
from __future__ import division
import sys
data = sys.stdin.readlines()
buffer = []
for d in data:
buffer.append(d)
a = buffer[0]
b = buffer[1]
p1 = (int(a)//int(b))
q1 = (int(a)/int(b))
m = str(p1)
n = str(q1)
print sys.stdout.write(m)
sys.stdout.flush()
print sys.stdout.write(n)
print sys.stdout.write(n). Pick one or the other.
print is printing the return value of sys.stdout.write(n) which is None.
My code looks like this:
Right now my code outputs two text file named absorbance.txt and energy.txt separately. I need to modify it so that it outputs only one file named combined.txt such that every line of combined.txt has two values separated by comma. The first value must be from absorbance.txt and second must be from energy.txt. ( I apologize if anyone is confused by my writting, Please comment if you need more clarification)
g = open("absorbance.txt", "w")
h = open("Energy.txt", "w")
ask = easygui.fileopenbox()
f = open( ask, "r")
a = f.readlines()
bg = []
wavelength = []
for string in a:
index_j = 0
comma_count = 0
for j in string:
index_j += 1
if j == ',':
comma_count += 1
if comma_count == 1:
slicing_point = index_j
t = string[slicing_point:]
new_str = string[:(slicing_point- 1)]
new_energ = (float(1239.842 / int (float(new_str))) * 8065.54)
print >>h, new_energ
import math
list = []
for i in range(len(ref)):
try:
ans = ((float (ref[i]) - float (bg[i])) / (float(sample[i]) - float(bg[i])))
print ans
base= 10
final_ans = (math.log(ans, base))
except:
ans = -1 * ((float (ref[i]) - float (bg[i])) / (float(sample[i]) - float(bg[i])))
print ans
base= 10
final_ans = (math.log(ans, base))
print >>g, final_ans
Similar to Robert's approach, but aiming to keep control flow as simple as possible.
absorbance.txt:
Hello
How are you
I am fine
Does anybody want a peanut?
energy.txt:
123
456
789
Code:
input_a = open("absorbance.txt")
input_b = open("energy.txt")
output = open("combined.txt", "w")
for left, right in zip(input_a, input_b):
#use rstrip to remove the newline character from the left string
output.write(left.rstrip() + ", " + right)
input_a.close()
input_b.close()
output.close()
combined.txt:
Hello, 123
How are you, 456
I am fine, 789
Note that the fourth line of absorbance.txt was not included in the result, because energy.txt does not have a fourth line to go with it.
You can open both text files and append them to the new text file as shown below. This is what I gave based on your question, not necessarily the code your provided.
combined = open("Combined.txt","w")
with open(r'Engery.txt', "rU") as EnergyLine:
with open(r'Absorbance.txt', "rU") as AbsorbanceLine:
for line in EnergyLine:
Eng = line[:-1]
for line2 in AbsorbanceLine:
Abs = line2[:-1]
combined.write("%s,%s\n" %(Eng,Abs))
break
combined.close()
I have a module with one method:
def find_inverse_matrix(C, log=False):
n = C.shape[0]
Cs = C.copy()
i = 0
C = np.matrix(np.eye(n))
B = np.matrix(np.eye(n))
J = set(range(n))
S = [0] * n
if log: print Cs
while i <= n-1:
if log: print '\nIteration', i
f = False
j = 0
ei = get_ek(i, n)
for j in J:
cj = get_ck(Cs, j)
alpha = (ei * B * cj)[0, 0]
if log: print 'alpha%s = %s' % (j, alpha)
if not(is_zero(alpha)):
f = True
break
if not(f):
exit('Inverse matrix is not exist')
J.remove(j)
S[j] = i
C[:, i] = Cs[:, j]
if log: print 'C%s:\n%s' % (i, C)
D = get_Dkz(i, B * C[:, i])
if log: print 'D%s:\n%s' % (i, D)
B = D * B
if log: print 'B%s:\n%s' % (i, B)
i += 1
if log: print '\n S = ', S
if log: print 'Result'
R = construct_matrix(B, S)
if log: print R
if log: print '\nCheck result:'
if log: print Cs * R
return R
If I call this method from this file it shows all print, but if I call if from another all print should be suppressed. Now I use check before every print, but how it do simple and pretty in 'pythonic' style?
Normally, print is a statement in the language. But if you add the line from __future__ import print_function to your imports then it is used as a function. This means two things:
a) You need to use this as a function - meaning print(Cs) instead of print Cs.
b) You can override it, since in python functions are objects you can play with.
You can define your own "my_print" functions which you can later change instead of the builtin print.
Example:
>>> from __future__ import print_function
>>> _print_ = print
>>> def myprint(*arg, **kwarg):
... _print_("yeah.")
... _print_(*arg,** kwarg)
...
>>> myprint("ok")
yeah.
ok
>>> print = myprint
>>> print('3')
yeah.
3
>>>
So just write your myprint function so that it'd check for "log" before, and your prints should be the same. Or just override print only when you don't want to suppress printing.
if __name__ == '__main__': will execute a block of code only if a file is executed directly, not loaded as a module. You can set a flag there to turn on logging.
A more pythonic way might be to pass a log function into the module instead of a flag. That way you could pass in an empty function to suppress logging.