Results 1 to 3 of 3

Thread: python script to restrict keyboard input to a specified length of characters

  1. #1
    Join Date
    Apr 2011
    Beans
    9

    python script to restrict keyboard input to a specified length of characters

    hi..
    i am trying to write a script, which accepts user input from keyboard. similar to this.
    http://stackoverflow.com/questions/8...rs-and-lengths

    however, my idea is to stop the cursor in the output terminal, after it reaches a specified length (say 16 characters).

    how do i do this? please help!

  2. #2
    Join Date
    Mar 2006
    Location
    Williams Lake
    Beans
    Hidden!
    Distro
    Ubuntu Development Release

    Re: python script to restrict keyboard input to a specified length of characters

    Moved to programming talk

  3. #3
    Join Date
    Feb 2008
    Beans
    251
    Distro
    Ubuntu 12.04 Precise Pangolin

    Re: python script to restrict keyboard input to a specified length of characters

    Not sure if you can to be honest... but probably the best thing is to handle the input afterwards:

    You can define an exception to do this, or just trim/delete the content as you see fit...

    Code:
    #!/usr/bin/env python
    
    class LengthError(Exception):
      def __init__(self, value): 
        self.value = value 
    
    user_input = raw_input("Enter 5 characters of text: ")
    
    if len(user_input) > 5:
      raise LengthError("Input stream too long")
      
    print user_input
    gives:

    Code:
    gp@mariachi:~$ ./error.py 
    Enter 5 characters of text: 12345
    12345
    gp@mariachi:~$ 
    gp@mariachi:~$ 
    gp@mariachi:~$ ./error.py 
    Enter 5 characters of text: 123456
    Traceback (most recent call last):
      File "./error.py", line 11, in <module>
        raise LengthError("Input stream too long")
    __main__.LengthError
    gp@mariachi:~$ 
    gp@mariachi:~$

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •