Thread: User Input

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    5
    Rep Power
    0

    User Input


    Hi, I'm having trouble oh how prompt the user to enter a file name and how to set up conditions. For example, if there's no file name input by the user, a default is returned
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,703
    Rep Power
    480
    Code:
    import sys
    
    def string_prompt(message, default, device = sys.stdin):
        '''
            When given white space as an answer, return the default.
            Otherwise, strip the input and return it.
            device is an object with a readline method.
            device is the source of the response.
            >>> import io
            >>> o = io.StringIO('   file name    \n')
            >>> print(string_prompt('message: ', 'ansys110', o))
            message: file name
            >>> print(string_prompt('message: ', 'ansys110', o))  # default because StringIO object o reached end of file.
            message: ansys110
        '''
        sys.stdout.write(message)
        result = device.readline().strip()
        return result or default
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2012
    Location
    39N 104.28W
    Posts
    157
    Rep Power
    2
    fname="/somedir/somefile.abc"
    chkname=raw_input("input filename [/somedir/somefile.abc]: ")
    if len(chkname)>0: fname=chkname
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    /dev/null
    Posts
    162
    Rep Power
    18
    A tad simpler (using python 3.x syntax):
    Code:
    x = input ('Enter filename: ')
    x = x.strip() or 'some_default_value'
  8. #5
  9. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,703
    Rep Power
    480
    It's also python2 syntax. And python1 syntax.

    x = input ('Enter filename: ')
    x = x.strip() or 'some_default_value'

    Comments on this post

    • Mekire agrees : input vs raw_input I believe was the point of contention.
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo