Re: Tips to match multiple patterns from from a single file .
You want to find strings on multiple lines of a file, and possible multiple string groups within a file (you didn't say). So you will have to check each line and store anything you want to keep for each file, and you will have to add the code to cycle through the files, so it is something along the lines of. def find_a_string(string_in, rec): return_str="" string_len=len(string_in) if string_in in rec: location=rec.find(string_in) start=location+string_len ## go until you find a space or end of line for letter in rec[start:]: if len(letter.strip()): return_str += letter else: return return_str return return_str test_file=test_data.split("\n") ## turn into data like file_handle.readlines() found_dict={} for rec in test_file: if len(rec.strip()): for str in ("offset=", "Data before corruption : ", "size="): found=find_a_string(str, rec) if len(found): found_dict[str]=found ## assume this always comes after the above strings in the file if "Corrupting disk object 6 at 1,1,25296896:8192" in rec: print "object 1,1,25296896:8192", for key in found_dict: print key.strip(), found_dict[key], print -- https://mail.python.org/mailman/listinfo/python-list
Re: error i m getting in line no 4
And you can simplify the code with something like this for all of the "grid=" statements new_grid = [[], [0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0], [2,0,2,0],[0,4,0,8],[0,16,0,128],[2,2,2,2], [0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]], [2,0,2,0],[0,4,0,8],[0,16,0,128],[2,2,2,2], [2,2,2,2],[2,2,2,2],[2,2,2,2],[2,2,2,2]] ## etc grid=new_grid[test] This also assumes that you want grid to be a list, and not a list of lists. -- https://mail.python.org/mailman/listinfo/python-list
Re: I need help with making my claculator
This is most likely using class objects instead of instance objects. Not a normal thing in Python. As stated above, it is difficult, as the responses in this thread show, to get assistance with some alternate coding style. It is better to use Python in the way that is intended. Otherwise, you can not expect volunteers to spend extra time trying to figure out someone's alternate style. -- https://mail.python.org/mailman/listinfo/python-list
Re: I need help with making my claculator
How do you then run the mainloop, i.e. get it to do something? -- https://mail.python.org/mailman/listinfo/python-list
Re: Concatenating files in order
It is very straight forward; split on "_", create a new list of lists that contains a sublist of [file ending as an integer, file name], and sort fnames=["XXX_chunk_0", "XXX_chunk_10", "XXX_chunk_1", "XXX_chunk_20", "XXX_chunk_2"] sorted_list=[[int(name.split("_")[-1]), name] for name in fnames] print "before sorting", sorted_list sorted_list.sort() print "after sorting ", sorted_list -- https://mail.python.org/mailman/listinfo/python-list
Re: I need help with making my claculator
First, you have to have a Tk instance before you do anything else. Take a look at this example, and then expand upon it to create the calculator http://python-textbok.readthedocs.io/en/1.0/Introduction_to_GUI_Programming.html -- https://mail.python.org/mailman/listinfo/python-list
Re: Alternative to signals in threads
Use multiprocessing since you want to do multiple things at once https://pymotw.com/2/multiprocessing/basics.html If I understand you correctly, once the string is found you would terminate the process, so you would have to signal the calling portion of the code using a Manager dictionary or list.. I am not that knowledgeable about multiprocessing, so this is probably the long way around the barn. import time from multiprocessing import Process, Manager def test_f(test_d): ctr=0 while True: ctr += 1 print "test_f", test_d["QUIT"], ctr time.sleep(1.0) if ctr > 5: test_d["QUIT"]=True if __name__ == '__main__': ## define the dictionary to be used to communicate manager = Manager() test_d = manager.dict() test_d["QUIT"] = False ## start the process p = Process(target=test_f, args=(test_d,)) p.start() ## check the dictionary every half-second while not test_d["QUIT"]: time.sleep(0.5) p.terminate() -- https://mail.python.org/mailman/listinfo/python-list
Re: correct way to catch exception with Python 'with' statement
If you want to do something only if the file exists (or does not), use os.path.isfile(filename) -- https://mail.python.org/mailman/listinfo/python-list
Re: csv into multiple columns using split function using python
Add some print statements to see what is happening, especially after the for elem in mylist1: statement -- https://mail.python.org/mailman/listinfo/python-list
Re: exit ThreadPoolExecutor immediately
Doug Hellmann has what looks like a similar example using a poison pill (2nd example at) https://pymotw.com/2/multiprocessing/communication.html#multiprocessing-queues Note that join() allows the processes to finish so it you don't care then don't "join()" them. You can also terminate a multiprocessing thread https://pymotw.com/2/multiprocessing/basics.html#terminating-processes -- https://mail.python.org/mailman/listinfo/python-list
Re: Removing matching items from a list?
Use a dictionary to count the number of times each first letter appears, then place any first letters==4 in a list or set and remove any items that have a first letter in the list/set (or keep items that are not in the set which is probably faster if using list comprehension). -- http://mail.python.org/mailman/listinfo/python-list
Re: 回复: FACTS: WHY THE PYTHON LANGUAGE FAILS.
Any programming language is only as good as the person who is using it. -- http://mail.python.org/mailman/listinfo/python-list
Re: python script is not running
The obvious question, do you have the shebang on the first line so the OS knows it's to be run as a Python program? Also I would change tryJson() to if __name__ == __main__': tryJson() This probably won't make any difference but you will have the bases covered. -- http://mail.python.org/mailman/listinfo/python-list
Re: kbhit/getch python equivalent
I'm looking for a kbhit/getch equivalent in python in order to be able to stop my inner loop in a controlled way (communication with external hardware is involved and breaking it abruptly may cause unwanted errors A curses example import curses stdscr = curses.initscr() curses.cbreak() stdscr.keypad(1) stdscr.addstr(0,10,Hit 'q' to quit ) stdscr.refresh() key = '' while key != ord('q'): key = stdscr.getch() stdscr.addch(20,25,key) stdscr.refresh() curses.endwin() -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting a click on the turtle screen when the turtle isn't doing anything?
waiting = False def clicked(x, y): global waiting print('clicked at %f %f' % (x,y)) waiting = False return def wait_for_click(s): global waiting waiting = True s.listen() while waiting: time.sleep(1) return ... t = turtle.Pen() s = turtle.Screen() ... traverse.plot(s, t, black, scale, adjx, adjy) wait_for_click(s) bowditch.plot(s, t, red, scale, adjx, adjy) wait_for_click(s) transit.plot(s, t, blue, scale, adjx, adjy) wait_for_click(s) Note that the code you posted does not call onclick(). Globals are confusing IMHO. Code becomes cleaner and easier to write and read when you become familiar with classes. import turtle class TurtleTest(): def __init__(self): self.ctr=0 t = turtle.Turtle() s = turtle.Screen() s.onclick(self.clicked) turtle.mainloop() def clicked(self, x, y): print self.ctr if 0 == self.ctr: self.first() elif 1 == self.ctr: self.second() elif 2 == self.ctr: self.third() self.ctr += 1 def first(self): print first called def second(self): print second called def third(self): print third called TT = TurtleTest() -- http://mail.python.org/mailman/listinfo/python-list
Re: error
From this line, data appears to be a class if 0 ix data.width and 0 iy data.height: From this line, data appears to be a list, although a two dimensional list would be accessed as data[ix][iy] point = data[ix, iy] Also, returning a list from a function is a matter of preference. Some people argue that it should be returned to make it obvious. If you do not know the difference between what is mutable and what is not mutable, then return everything until you do. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter how to access the widget by name
On Oct 14, 1:11 pm, Владимир Пылев clinicalf...@gmail.com wrote: label = Label(frame, width = 40, text='text', name = 'name') ... name_='name' configure(name_) ... def configure(name_) #And how can that be? # At least let the text you want to change I do not understand your question, but I think you want something like def configure(name): ## note that a colon is required here name.configure(bg='green') # or name['bg']='green' label_1 = Label(frame, width = 40, text='text') configure(label_1) label_2 = Label(frame, width = 40, text='label_2') configure(label_2) If this is not what you want, post an example that is more specific. -- http://mail.python.org/mailman/listinfo/python-list
Re: Unpaking Tuple
On Oct 6, 3:09 am, sajuptpm sajup...@gmail.com wrote: I need a way to make following code working without any ValueError . a, b, c, d = (1,2,3,4) a, b, c, d = (1,2,3). Why is it necessary to unpack the tuple into arbitrary variables. a_tuple=(1,2,3) for v in a_tuple: print v for ctr in range(len(a_tuple)): print a_tuple[ctr] -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess call is not waiting.
It possibly requires a shell=True, but without any code on any way to test, we can not say. -- http://mail.python.org/mailman/listinfo/python-list
Re: submit jobs on multi-core
There is parallel python as well http://www.parallelpython.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary into desired variable....
On Friday, August 10, 2012 8:31:48 AM UTC-7, Tamer Higazi wrote: let us say a would be x = [2,5,4] y = a[3] if I change y to [] I want the result to be x = [2,5,[]] and that's automaticly There is no such thing as a[3] if a=[2,4,5]. And this is a list not a dictionary, so I would suggest a tutorial from the Python wiki page. You have to use a mutable container. Integers are not mutable. Lists, for example are. y=[4] x = [2,5,y] print x y[0]=10 print x -- http://mail.python.org/mailman/listinfo/python-list
Re: Blank TK Window
On Jul 17, 9:32 am, Shamefaced manengstud...@gmail.com wrote: Hi, Any reason why a blank Tk() window opens up when I run my code: Code: for run in range(RUNS): waittime = Monitor2() checkouttime = Monitor2() totaltimeinshop = Monitor2() checkout_aisle = Simulation.Resource(AISLES) Simulation.initialize() cf = Customer_Market() Simulation.activate(cf, cf.run(), 0.0) Simulation.simulate(until=CLOSING) Histo = waittime.histogram(low=0.0, high=80, nbins=40) plt = SimPlot() plt.plotLine(Histo, xlab='Time (min)',ylab='Qty Customers', title=Wait Time, color=red, width=2, smooth='True') plt.mainloop() 1. you no longer have a toplevel/root plt once you replace plt with plt = SimPlot() 2. the SimPlot widget in never placed in Tkinter. This is usually done with pack() or grid() So start out with a Tkinter tutorial so you understand the basics. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question:Programming a game grid ...
On Wednesday, June 27, 2012 5:15:09 PM UTC-7, Steven D#39;Aprano wrote: On Wed, 27 Jun 2012 16:24:30 -0700, David wrote: First, you should be getting an error on vars()[var] = Button(f3, text = 00, bg = white) as vars() has not been declared The Fine Manual says differently: Python 2: http://docs.python.org/library/functions.html#vars Python 3: http://docs.python.org/py3k/library/functions.html#vars and it does not appear to be valid Python syntax. It's perfectly fine syntax, no different from: my_dict['spam'] = 'a yummy ham-like substance' or similar. -- Steven as vars() has not been declared and it does not appear to be valid Python syntax You assume too much IMHO. Vars() was not declared in the code provided and I do not think that we should be assuming that it is a function returning a dictionary instead of an error. Just my opinion. -- http://mail.python.org/mailman/listinfo/python-list
Re: problems with tkinter updates
if line is not None: probably does not work the way you expect. You might try if line.strip(): Take a look at this quick example test_lines = [Number 1\n, \n, ] for ctr, line in enumerate(test_lines): print ctr, line if line is not None: print not None -- http://mail.python.org/mailman/listinfo/python-list
Re: += does not work correct all alogn
def conc1(a, _list = []): _list = _list + [a] return _list for i in range(4): _list = conc1(i) ## - list not passed You don't pass the list to the conc1 function, so you start with the default, an empty list, each time. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why widgets become 'NoneType'?
The error is with the labels not the canvas. All labels will have an id of None as that is what pack() returns. lbl = Label(win, text=astr[i]).pack(side=LEFT ) labels.append(lbl) The error will come up in the config_labels function when the program tries to config a tuple of None, if not before. Other than that, the previous suggestion, post the entire error message so we know where an what is happening, is required to debug further. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus
Adding focus_set seems to work for me. What do want to do differently? import Tkinter class demo: def __init__(self, parent): self._entry = Tkinter.Entry(width = 60) self._suggestions = Tkinter.Menu(parent, tearoff = 0, takefocus = 0) self._entry.pack(padx = 20, pady = 20) self._entry.bind('Key', self._suggest_text, add = '+') self._entry.focus_set() def _suggest_text(self, event): curr = self._entry.get() + repr(event.char)[1] x = self._entry.winfo_rootx() y = self._entry.winfo_rooty() y += self._entry.winfo_height() try: self._suggestions.delete(0, 'end') self._suggestions.add_command(label = curr + '_1') self._suggestions.add_command(label = curr + '_2') self._suggestions.add_command(label = curr + '_3') self._suggestions.add_command(label = curr + '_4') self._suggestions.post(x, y) finally: self._suggestions.grab_release() if __name__ == '__main__': root = Tkinter.Tk() root.title('A Problem') demo(root) root.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus
Sorry, I did not understand the question correctly, and so have added another focus_set for the entry after the menu's creation. You can still enter after the menu comes up, even though you can't see where you are entering. import Tkinter class demo: def __init__(self, parent): self._entry = Tkinter.Entry(width = 60) self._suggestions = Tkinter.Menu(parent, tearoff = 0, takefocus = 0) self._entry.pack(padx = 20, pady = 20) self._entry.bind('Key', self._suggest_text, add = '+') self._entry.focus_set() def _suggest_text(self, event): curr = self._entry.get() + repr(event.char)[1] x = self._entry.winfo_rootx() y = self._entry.winfo_rooty() y += self._entry.winfo_height() try: self._suggestions.delete(0, 'end') self._suggestions.add_command(label = curr + '_1') self._suggestions.add_command(label = curr + '_2') self._suggestions.add_command(label = curr + '_3') self._suggestions.add_command(label = curr + '_4') self._suggestions.post(x, y) finally: self._suggestions.grab_release() self._entry.focus_set() if __name__ == '__main__': root = Tkinter.Tk() root.title('A Problem') demo(root) root.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: Text file with mixed end-of-line terminations
You can use f.read() to read the entire file's contents into a string, providing the file isn't huge. Then, split on \r and replace \n when found. A simple test: input_data = abc\rdef\rghi\r\njkl\r\nmno\r\n first_split = input_data.split(\r) for rec in first_split: rec = rec.replace(\n, ) print rec -- http://mail.python.org/mailman/listinfo/python-list
Re: about if __name == '__main__':
Two main routines, __main__ and main(), is not the usual or the common way to do it. It is confusing and anyone looking at the end of the program for statements executed when the program is called will find an isolated call to main(), and then have to search the program for the statements that should have been at the bottom of the program. The only reason to use such a technique in Python is if you want to call the function if the program is run from the command line, and also call the same function if the program is imported from another. In which case, use a name that is descriptive, not main. And be careful of anyone that gives you programming advice. Research these things for yourself. -- http://mail.python.org/mailman/listinfo/python-list
Re: relative speed of incremention syntaxes (or i=i+1 VS i+=1)
as the += notation seems to be a syntaxic sugar layer that has to be converted to i = i + 1 anyway. That has always been my understanding. The faster way is to append to a list as concatenating usually, requires the original string, accessing an intermediate block of memory, and the memory for the final string. x_list.append(value) to_string = .join(x_list) -- http://mail.python.org/mailman/listinfo/python-list
Re: Can someone help please
On Jul 21, 10:02 am, Gary woody...@sky.com wrote: For some reason it will not send me the first text file in the directory. You have to print an unsorted list of the directory to know the name or the first file in the directory. Files are not stored on disk in alphabetical order, but are many times sorted in alphabetical name order by a program that lists the directory. Note that if you want the first file alphabetically, you can sort the list returned by listdir() and then look for the first .txt file. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonic way with more than one max possible
1. In this dict, if there is a UNIQUE max value, then its *key* is the winner. 2. If there are any TIES for max value, then the *key* 'b' is the winner by default. This will store the max value(s) in a list. In case of a tie, you can take the first value in the list, but it may be different than 'b' since dictionary keys are in hash order, not in the order they were entered. You can decide if you want the smallest key, or whatever criterion is best. the_dict = {'a':1, 'b':2, 'c':0, 'd':1, 'a0':2} winners = [['*', -999]] for key in the_dict: max_value = winners[0][1] ## only lookup once dict_value = the_dict[key] ## if dict_value max_value: winners = [[key, dict_value]] elif dict_value == max_value: winners.append([key, dict_value]) print winners -- http://mail.python.org/mailman/listinfo/python-list
Re: Partial Function Application -- Advantages over normal function?
Partial can be used in a GUI program, like Tkinter, to send arguments to functions. There are other ways to do that as well as using partial. The following program uses partial to send the color to the change_buttons function. from Tkinter import * from functools import partial class App: def __init__(self, parent): self.my_parent = parent self.my_parent.geometry(200x100+10+10) self.R = list() for ctr, color in enumerate((Red, Blue, Green)): btn = Radiobutton(self.my_parent, text=color, value=ctr+1, command=partial(self.change_buttons, color)) btn.grid(row = 2, column = ctr+1) btn.deselect() self.R.append(btn) self.R[0].select() self.change_buttons(Red) def change_buttons(self, color): self.my_parent.configure(bg=color) for btn in self.R: btn.configure(bg=color) if __name__ == __main__: root = Tk() root.title (Color Option) app = App(root) root.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: update of elements in GUI
On Aug 16, 9:07 pm, Jah_Alarm jah.al...@gmail.com wrote: hi, I've already asked this question but so far the progress has been small. I'm running Tkinter. I have some elements on the screen (Labels, most importantly) which content has to be updated every iteration of the algorithm run, e.g. Iteration = [i] for i in range(n), n=100. I'm using the update_idletasks() command in the function itself after the variable.set(...) command. The variable type is IntVar(), and the mistake I'm getting is 'IntVar instance has no attribute 'update_idletasks'. No updates are displayed, of course. Without the GUI the algorithm (it's a genetic algorithm) is working fine, but I need to make it available to other people via GUI cheers, Alex This program I had lying around and it will hopefully make things clearer. The integer under the second label (i.e. the 3rd label) increases by on every time you click the Print Contents button. The variable associated with the second label and the entry box update as you change the entry box's contents, all with no calls to update_idletasks(). class EntryTest: shows using the same StringVar in the second list box and in the entry box def __init__(self): self.top = Tkinter.Tk() self.top.title(Test of Entry) self.top.geometry(200x150+10+10) self.str_1 = Tkinter.StringVar() label_lit = Tkinter.StringVar() self.int_lit = Tkinter.IntVar() label_1 = Tkinter.Label(self.top, textvariable = label_lit ) label_1.pack() label_lit.set( Test of Label) label_2 = Tkinter.Label(self.top, textvariable = self.str_1 ) label_2.pack() label_3 = Tkinter.Label(self.top, textvariable = self.int_lit ) label_3.pack() self.int_lit.set(0) entry_1 = Tkinter.Entry(self.top, textvariable=self.str_1) entry_1.pack() self.str_1.set( Entry Initial Value ) print_button = Tkinter.Button(self.top, text='PRINT CONTENTS', command=self.getit, bg='blue', fg='white' ) print_button.pack(fill=Tkinter.X, expand=1) exit_button= Tkinter.Button(self.top, text='EXIT', command=self.top.quit, bg='red', fg='white' ) exit_button.pack(fill=Tkinter.X, expand=1) entry_1.focus_set() self.top.mainloop() ##- def getit(self) : print getit: variable passed =, self.str_1.get() x = self.int_lit.get() self.int_lit.set(x+1) ##=== if __main__ == __name__ : ET=EntryTest() print under __main__ =, ET.str_1.get() -- http://mail.python.org/mailman/listinfo/python-list
Re: update of elements in GUI
On Aug 16, 9:07 pm, Jah_Alarm jah.al...@gmail.com wrote: I have some elements on the screen (Labels, most importantly) which content has to be updated every iteration of the algorithm The variable type is IntVar() You would use int_var_name.set(some_number) -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQT 4.6.2 question about radiobuttons
QT uses toggled. I do not use QT much but it would be something like self.radioButton_one.setCheckable(True) QtCore.QObject.connect(self.radioButton_one, QtCore.SIGNAL(toggled ()),self.button_one_function) If this doesn't work, you can probably find more with a Google for toggled. -- http://mail.python.org/mailman/listinfo/python-list
Re: read file with multiple data per line
If this is the record, then you can use split to get a list of the individual fields and then convert to int or float where necessary. rec = 2NHST1 C1 56 3.263 2.528 16.345 rec_split = rec.split() print rec_split If you want to read two records at a time, then use all_data = open(name, r).readlines() to read all data into memory, given that the file isn't huge. You can then use a for loop, step=2, to access 2 records at a time. -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
Counting from zero through n-1 is used because it is the memory offset and not any kind of counter. Simplified, if you are iterating through a list, using a for loop or anything else, the first element/number is at memory offset zero because it is at the beginning. And if this is a list of 4 byte integers, the offset for the second element is 1*4 bytes, etc. This idea, that somehow the first element of a list is the zero element is a fairly recent abnormality AFAIK. It perhaps comes from assumptions by people who are not familiar with what happens inside of a programming language, assuming incorrectly, that the (programming) world was created in their own image, and so programming languages were generated in the way that they think they were. This is a bad assumption for any programmer. Instead one should get in the habit of saying, in general as well as in this specific case, This doesn't make sense. I wonder how __I__ screwed this up. Hopefully this will be helpful advice. Taking the attitude that you have screwed up yet again will get to the heart of the problem, and save many hours of frustration wondering why this language/computer doesn't do what it is supposed to do. -- http://mail.python.org/mailman/listinfo/python-list