I am working on a problem where i should collect data from running program numerous times. For example, every time the program finishes commands, it give certain value t, which is different every time run it. My task is to collect t from N runs of the program. t is going to be different every run. here is the program:
import random
th=0
t=0
tr=0
result=[]
for i in range(7):
i=random.randint(0,1)
result.append(i)
print(result)
a=0
b=len(result)-1
while th<50:
j=random.randint(a,b)
i=j-1
k=j+1
if k<b
k=0
if result[i]==result[k]:
if result[j]!=result[i]:
result[j]==result[i]
th=0
t+=1
else:
th+=1
t+=1
else:
th+=1
t+=1
tr= t-th
print(tr)
print (result)
In this program every run gives you new result. In this generated array there will be obviously every time different arrangement of 0 and 1 and therefore, different t. So resulting t, tr, will be ofcourse different.
I don't know wheter i should do it in new window, or there is a certain function that can do this. Also, if this question is to easy, and there is literature for it, please write what is the name of this kind of problem. thanks :)
btw, im working in python 3.6
See how to make one Python script launch another: you can write a Python script to run the other script and gather the output. You can receive the output as return value from a function call, and tally it just as you would from any function.
Note that your "running program" and your master script need to agree on the form of the information returned: know the data types you're receiving. If you're in doubt, start by having your master script print out what it receives, and the type of each returned value.
Related
display expression: prints out the value of an expression each time it gets changed. This is useful for monitoring the value of variables that get changed in loops. So, suppose the following is the code:
for i in range(100):
for j in range(100):
a=f(i,j)
I know something is wrong with the execution of a=f(i,j) for certain values of i and j. Then, how to use the display command from pdb module to find out the values of i and j when it does not work? I suppose when you use display command, it will display the value of i and j automatically, right? Do I need to combine the c command and b command from pdb module also? Many thanks for your time and attention.
display sets a "watch", so that each time execution stops (whether by completing a next, a step, or an until, or breaking on a continue ), if the value has changed, it will print a message showing the old value and the new value.
Since you know something is wrong with your f function, your easiest solution is to put a break on that function, and set display of the inputs inside that scope. Since you have shown us nothing about f, I don't know what the input variables will be called at that level, but it's likely that it won't be "i" and "j", so set the display appropriately.
I find display most useful for when I'm stepping through code that involves loops, using n or s or c. It keeps track of variables for me, and saves me from having to print the variables I'm interested in. If you know your problem is in f, you'll have to step through the code there yourself, and check all the variables at all the interesting statements. If you find yourself checking a variable repeatedly, that's where you use display.
This is probably a dumb question, but I'm new to programming and I have a recursive function set up that I'm trying to figure out. For any print function in Python, is it necessarily true that lines are printed in the order that they are written in the script OR for larger outputs, is it possible that smaller length outputs can get printed first in the console even though the print statement is later in the code (maybe due to some memory lag)?
Example:
def test_print():
#don't run this, but was meant for scale. Is there any chance the 1 would print before the list of lists?
print([[i for i in range(10000)] for j in range(10000)])
print(1)
Print statements pile output into stdout in the order the code was written. Top to bottom. It isn't possible any other way because that's the way the code is interpreted. Memory lag doesn't play any role here because the output to your console is a line for line rendition of the data that was piled into stdout. And the order the data was written to it can't change, so you'll maintain chronology. Of course, you can always play around with the how the print function itself works. But I wouldn't recommend tampering with standard library functions.
As said above, print() function is executed in the order which they are in your code. But you yourself can change the order in which you want it executed, after all you have every right to instruct the code to do whatever you want.
You'll always get the same order in the output as the order you execute print() functions in Python.
I have a code where I iterate a certain scheme using a loop. At each iteration I want a printout of what happened. A silly minimal working example is shown below:
import time
Iter=0
for k in range(1,10):
Iter=Iter+1
print('At iteration ',Iter,': k=',k,'.',sep='')
time.sleep(1)
The time.sleep(1) is there to make my problem visible for such a short iteration scheme: At each iteration, the print() function only prints the first string. The rest appears only after the print() function is called in the next iteration. If I use the exact same syntax for the print() function outside of the loop, then I obtain the output I want. How can I get the same output when I'm inside the loop?
I'm new at this, but I suspect it could be relevant that I use the Anaconda3 (64-bit) distribution of Python 3.5 with the Spyder IDE on a Win10 machine.
Edit 1: SOLVED using the suggestion by #RemcoGerlich: "Try adding 'import sys' and then after the print sys.stdout.flush()." Many thanks!
I´m a begginer with python, and I hope that somebody can help me with this, I´m in a stack. I´m writing a simple code that conects with an odometer by ITCIP, recive data, process it and store in a dictionary, when some defined distance is reached the while loop breaks and return a dictionary with the data. These function works perfect alone.
The problem comes when I want to execute the function from a GUI with Tkinter, I assign the function to a button, when the button is pressed the function starts, but is blocked in the last loop, if I close the GUI the function show the data in the console, but doesn´t return the dictinary, any error appears. I try with "lambda:", without it, executing an external script with "execfile()", calling the function in a external file, and the functions never ends. Only when ist breaked with Crt+c. Here is a reduced code of "odom.py":
from Tkinter import *
import socket
from datetime import datetime, timedelta
v0=Tk()
v0.config(bg="gray")
v0.geometry("400x300")
v0.title("GUI")
def func():
ITCIPadress='172.17.18.21'
port=6000
i=0 #initialize the dictionary
rueda = {i:{
'position':i,
'distance':i}}
distancetomeasure=float(raw_input("distance to measure(in m): "))
dist=float(0)
distincr=float(0)
rev=0.5 ##odometer wheel circunference in meter
stepsrev=8192.0#Number of steps/revolution in the odometer
s = socket.socket()
s.connect((ITCIPadress, port))
while dist<=distancetomeasure: #It works in positive and negative direction
recibido = s.recv(45)#number of bytes recived
print "Recibido:", recibido
Postime_tmp=map(int, re.findall('\d+', recibido))#split the data
position_tmp=int(Postime_tmp[0])
rueda.update({i:{'position':Postime_tmp[0],
'distance':dist}})
if i>0: #because when i=0 there is no increment
incr_tmp=(rueda[i]['position']-rueda[i-1]['position'])
distincr=(incr_tmp/stepsrev)*rev
print distincr
dist=dist+distincr
print 'the distance till yet is:', dist
rueda.update({i:{'position':Postime_tmp[0],
'distance':dist}})
i=i+1
print "the distance from start point is:", dist
s.close()
return rueda
b1=Button(v0,text='Start the odometer',command= lambda: func())
b1.pack(fill=BOTH, expand=1) #command= execfile(C:\odometer.py)[calling another file with the function]
v0.mainloop() #command= lambda: odometer.measuredistance()[calling another file with the function]
#if __name__ == '__main__':
# rueda = func()
If I comment the part of the GUI, and unblock the last two lines, it works perfectly, but within a GUI doesn´t. I cannot understand why this behavior happens.
This is with the GUI, measuring 1 meter, it stacks on the last:
0.037109375
the distance till yet is: 0.896179199219
Recibido: POSITION=25403046 TIMESTAMP=104308321
0.0422973632812
the distance till yet is: 0.9384765625
Recibido: POSITION=25403756 TIMESTAMP=104502033
0.0433349609375
the distance till yet is: 0.981811523438
Recibido:
and this is executing only the function, measuring 1 meter too:
0.037109375
the distance till yet is: 0.896179199219
Recibido: POSITION=25403046 TIMESTAMP=104308321
0.0422973632812
the distance till yet is: 0.9384765625
Recibido: POSITION=25403756 TIMESTAMP=104502033
0.0433349609375
the distance till yet is: 0.981811523438
Recibido: POSITION=25404477 TIMESTAMP=104705956
0.0440063476562
the distance till yet is: 1.02581787109
the distance from start point is: 1.02581787109
this last one returns also the dictionary with all the interest values. Any help will be grateful! Thanks
the reason you are not seeing anything returned is that it effectively gets returned to the button you are using to call the function, as #Yann says, you should try and build up your GUI to do the entire of your program, otherwise there is little point to having both a GUI and command line visible to the user
First of all, you should not use a raw_input inside a function called by a GUI. Instead, try to build your GUI, with an input field for your 'distancetomeasure' variable.
After that, instead of returning the results, why not building another widget GUI to display these ?
It's been a long time since I last used Tkinter, but it's a nice GUI, and you should, if you have the time, how to build a nice app by visiting http://effbot.org/tkinterbook/tkinter-index.htm for example.
But if you're in a hurry, I'm sure other fellows here will gladly help you :)
This is the continuation of my previous question where it was not that clear what I want to do.
Now please find the Full code here I know this code is very crude as I am new to programming . I am sure this code can be written in another way more optimally but I am not that experienced.
Now my question is I will be running this code from Python shell.
while 1 ==1:
execfile('adhocTest.py')
This code consists of two parts 1. Prerequisite 2. Main program.
The prerequisite is to copy a template Excel file and paste in a directory. Main program is to do some operation and result should be written onto this file and validate few cells. If the condition is true main program will keep continuing else I want that whole script should run again i.e Run pre requisite as well as main program. I am stuc at this point as of now if teh condition is false it exits the whole script.
As I said this code is crude if anyone helps me to optimize it I will be very happy. But this is secondary. I need the continuous run of this script when the condition is false.
You need to re-structure your program:
def call_me():
while True:
prerequisite()
main_operations()
if validate():
main_continuing()
or
def call_me():
while True:
prerequisite()
while validation():
main_operations()
This will loop around as you need it to.