Re: Turtle window not closing

2017-04-23 Thread Peter Otten
Harshika Varadhan via Python-list wrote:

> Thank you for your response. I apologize for that, this is my first time
> posting so I wasn't sure how to copy my code! I figured out that using the
> clear() method works for clearing the turtle window after drawing the game
> board, but now I am trying to figure out how to make the program wait a
> few seconds or wait for the user to press a key before clearing the turtle
> window (not closing the window, just clearing it). Is there any way to do
> this?

I experimented a bit and found the Screen.ontimer() and onkey() methods. 
Those take a function (a "callback") that will be executed after a certain 
time or when the specified key is pressed. Here are two simple example 
scripts:

demo_turtle_timer.py
# Draw a square, then remove it after two seconds
import turtle

def draw_board():
myturtle.showturtle()

# draw a square
# replace with your code
for i in range(4):
myturtle.forward(100)
myturtle.right(90)

def clear_board():
myturtle.clear()
myturtle.hideturtle()

myturtle = turtle.Turtle()
screen = turtle.Screen()

draw_board()

# clear board after 2 seconds
screen.ontimer(clear_board, 2000)

screen.mainloop()

demo_turtle_key.py
# Hit d to draw a square, then hit c to remove it
import turtle

def draw_board():
myturtle.showturtle()

# draw a square
# replace with your code
for i in range(4):
myturtle.forward(100)
myturtle.right(90)

def clear_board():
myturtle.clear()
myturtle.hideturtle()

myturtle = turtle.Turtle()
screen = turtle.Screen()

# invoke clear_board() when the c key is pressed
screen.onkey(clear_board, "c")

# invoke draw_board() when the d key is pressed
screen.onkey(draw_board, "d")

screen.listen()
screen.mainloop()


-- 
https://mail.python.org/mailman/listinfo/python-list


any suggestion on this code

2017-04-23 Thread Ganesh Pal
Hello  Team,



I have a sample code that runs through the list of dictionary and return a
dictionary if the search  value matched



*Sample Program:*



#!/usr/bin/python



def return_matched_owner(dict_list,search_block):

"""Accepts a list of dictionary with owners and returns a dict if there
is a match"""

try:

x = next(item for item in dict_list if item.get("Block") ==
search_block)

except StopIteration:

return False

return x





def main():

dict_list = [{'real_owner': '1:0070', 'fake_owner': '121212aaa',
'Block': '121212121'},

 {'real_owner': '1:0170', 'fake_owner': 'aaa', 'Block':
'21115674'},

 {'real_owner': '1:0120', 'fake_owner': 'ab', 'Block':
'31115674'}]



x =  return_matched_owner(dict_list,'31115674')

print x

if not x:

   assert False, "Error while getting owner"

print "\n Matching owner found \n"





if __name__ == '__main__':

main()





*Sample o/p:*



yy-1# python stack1.py

{'real_owner': '1:0120', 'fake_owner': 'ab', 'Block': '31115674'}



 Matching owner found





Couple of question here :



1.  Any better suggestion to optimize the code  and any other
observations  around use of assert, generators  and are exception handled
correctly in  return_matched_owner()





Regards,

Ganesh
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: In Python and Windows environment how to supress certain key press and send some other key event for it

2017-04-23 Thread J. Clarke
In article , 
[email protected] says...
> 
> Hi All,
> 
> I was trying to build a VIM like shortcuts in windows. For example,
> 
> IF i press CAPSLOCK & h: It should "{Left}" move one to left. If CAPSLOCK &
> b: It should "{Ctrl Down}{Left}{Ctrl Up}" move one word left etc.
> 
> I was successful in sending the key event. I used libraries like,
> 
> 1. pynput
> 2. keyboard
> 
> for the same.
> 
> But i was unable to supress the Initial key event (ex: Caplock & h)
> 
> I tried using the keyboard to listen for key press events and supress them
> as below.
> 
> >
> import keyboard
> 
> def move_one_left():
> """
> Wrapper for CAPS LOCK + b. The function sends LEFT ARROW Event
> :return:
> """
> keyboard.send(75)
> 
> def move_one_word_left():
> """
> Wrapper for CAPS LOCK + b. The function sends LEFT ARROW Event
> :return:
> """
> keyboard.send('ctrl+left')
> 
> def main():
> """
> This is the main loop which reads the key pressed.
> According to the hotkey registered the function hooked is called.
> The corresponding function will be the wrapped combination send back.
> For example: CAPS + b is wrapped to Moving to left.
> The main loop exits when Ctrl + c is done. So that is not registered.
> :return:
> """
> try:
> # Start of the main loop
> # Registering the hotkeys
> # CAPS LOCK + H
> keyboard.add_hotkey('caps lock+h', move_one_left, suppress=True)
> # CAPS LOCK + B
> keyboard.add_hotkey('caps lock+b', move_one_word_left,
> suppress=True)
> 
> while True:
> # Read the key pressed
> print (keyboard.read_key())
> except KeyboardInterrupt:
> print("User has exited the program")
> 
> if __name__ == "__main__":
> main()
> 
> <
> 
> 
> This is working for sending the event for key press but the initial
> keypress is also being send. The supress=True is not working.
> 
> Am I doing something wrong or is there any better way to supress the
> initial key event and send another key event in place of that.



Check the "known limitations" section.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: any suggestion on this code

2017-04-23 Thread MRAB

On 2017-04-23 09:21, Ganesh Pal wrote:

Hello  Team,


I have a sample code that runs through the list of dictionary and return a
dictionary if the search  value matched


*Sample Program:*


#!/usr/bin/python


def return_matched_owner(dict_list,search_block):

 """Accepts a list of dictionary with owners and returns a dict if there
is a match"""

 try:

 x = next(item for item in dict_list if item.get("Block") ==
search_block)

 except StopIteration:

 return False

 return x


def main():

 dict_list = [{'real_owner': '1:0070', 'fake_owner': '121212aaa',
'Block': '121212121'},

  {'real_owner': '1:0170', 'fake_owner': 'aaa', 'Block':
'21115674'},

  {'real_owner': '1:0120', 'fake_owner': 'ab', 'Block':
'31115674'}]


 x =  return_matched_owner(dict_list,'31115674')

 print x

 if not x:

assert False, "Error while getting owner"

 print "\n Matching owner found \n"


if __name__ == '__main__':

 main()


*Sample o/p:*


yy-1# python stack1.py

{'real_owner': '1:0120', 'fake_owner': 'ab', 'Block': '31115674'}


  Matching owner found


Couple of question here :


1.  Any better suggestion to optimize the code  and any other
observations  around use of assert, generators  and are exception handled
correctly in  return_matched_owner()

If it's going to return a dict or something else, it's more usual for 
that "something else" to be None.


I think that the function is needlessly complicated and that this is better:


def return_matched_owner(dict_list,search_block):
 """Accepts a list of dictionary with owners and returns a dict if 
there is a match"""


for item in dict_list:
if item.get("Block") == search_block:
return item

 return None
--
https://mail.python.org/mailman/listinfo/python-list


Re: String escaping utility for Python (was: Rawest raw string literals)

2017-04-23 Thread Mikhail V
On 23 April 2017 at 05:03, MRAB  wrote:
> On 2017-04-22 23:30, Mikhail V wrote:
>>
>> On 20 April 2017 at 23:54, MRAB  wrote:
>> > On 2017-04-20 22:03, Mikhail V wrote:
>> >>
>> >> On 20 April 2017 at 22:43, Random832  wrote:
>> >>> [snip]
>> >>>
>> >>> The best solution I can think of is to have a text editor designed to
>> >>> parse a string literal, spawn a nested editor with the unescaped
>> >>> contents of that string literal, and then re-escape it back to place
>> >>> in
>> >>> the code. If we had that, then we wouldn't even need raw strings.
>> >>
>> >>
>> >> Yes exactly, it would be cool to have such a satellite app
>> >> which can escape and unescape strings according to rules.
>> >> And which can also convert unicode literals to their ascii
>> >> analogues and back on the fly, this would very useful
>> >> for programming.
>> >> Probably it is a good idea to even include such thing
>> >> in Python package. So it would be a small standalone app
>> >> running parallel with text editor making it to copy paste strings.
>> >>
>> > I'm sure it's possible in, say, Emacs.
>> >
>> > The editor that I use (EditPad Pro) can call external tools, so I could:
>> >
>> > 1. Select the string literal (easy when it is syntax-aware, so I can
>> > select
>> > all of the literal with 2 keypresses).
>> >
>> > 2. Call the external tool (1 keypress), to open, say, a simple tkinter
>> > app.
>> >
>> > 3. Edit the unescaped text (unescape with ast.literal_eval, re-escape
>> > with
>> > 'ascii').
>> >
>> > 4. Close the external tool, and the selection is replaced.
>>
>> I have done a quick google search and could not find
>> such utility for Python.
>>
>> I am very interested in having such utility.
>> And I think it would be fair that such utility
>> should be made by the Python team so that
>> all syntax nuances will be correctly implemented.
>>
>> The purpose is simple: reduce manual work to escape special
>> characters in string literals (and escape non-ASCII characters).
>>
>> Simple usage scenario:
>> - I have a long command-line string in some text editor.
>> - Copy this string and paste into the utility edit box
>> - In the second edit box same string with escaped characters
>>appears (i.e tab becomes \t, etc)
>> - Further, if I edit the text in the second edit box,
>>an unescaped string appears in the first box.
>>
>> Possible toggle options, e.g. :
>> - 'asciify' non-ascii characters
>>
>> It could be not only useful to eliminate boilerplate typing,
>> but also a great way to learn string rules for Python learners.
>>
> Here's a very simple tkinter GUI app. It only goes one way (plain to escaped
> (asciified)), but it shows what's possible with very little code.
>
>
> #! python3.6
> # -*- coding: utf-8 -*-
> import tkinter as tk
>
> class App(tk.Tk):
> def __init__(self):
> tk.Tk.__init__(self)
> self.title('Escaper')
>
> tk.Label(self, text='Plain string').pack()
>
> self.plain_box = tk.Text(self)
> self.plain_box.pack()
> self.plain_box.focus()
>
> tk.Label(self, text='Escaped string').pack()
>
> self.escaped_box = tk.Text(self)
> self.escaped_box.pack()
>
> self.after(100, self.on_tick)
>
> def on_tick(self):
> plain_string = self.plain_box.get('1.0', 'end')[ : -1]
>
> escaped_string = ascii(plain_string)
>
> self.escaped_box.delete('1.0', 'end')
> self.escaped_box.insert('1.0', escaped_string)
>
> self.after(100, self.on_tick)
>
> App().mainloop()
>

Thank you for sharing! Works fine on Win 7.
So that is what I mean, even such simple app is
uncomparably better that any workarounds and already
covers most cases.
Unfortunately I am not proficient in tkinter so I hope
that will gain some support from other folks and then
could be pinned somewhere and be accessible for
everyone.


Mikhail
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: any suggestion on this code

2017-04-23 Thread Steve D'Aprano
On Sun, 23 Apr 2017 06:21 pm, Ganesh Pal wrote:

> 1.  Any better suggestion to optimize the code  and any other
> observations  around use of assert, generators  and are exception handled
> correctly in  return_matched_owner()

When to use assert:

http://import-that.dreamwidth.org/676.html




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

-- 
https://mail.python.org/mailman/listinfo/python-list