No file from stdin

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tartifola

    #1

    No file from stdin



    Hi,
    suppose a script of python is waiting for a file from the stdin and none
    is given. How can I make the script to stop and, for example, print an
    error message?

    Sorry for the n00b question and thanks
  • aspineux

    #2
    Re: No file from stdin

    On 24 mai, 18:48, Tartifola <tartif...@gmai l.comwrote:
    Hi,
    suppose a script of python is waiting for a file from the stdin and none
    is given. How can I make the script to stop and, for example, print an
    error message?
    >
    Sorry for the n00b question and thanks
    import sys
    import os.path

    if len(sys.argv)<2 :
    print >>sys.stderr, 'Usage: %s filename' %
    (os.path.basena me(sys.argv[0]),)
    sys.exit(1)

    print 'Your filename is %s' % (sys.argv[1],)


    Comment

    • Matimus

      #3
      Re: No file from stdin

      On May 24, 9:48 am, Tartifola <tartif...@gmai l.comwrote:
      Hi,
      suppose a script of python is waiting for a file from the stdin and none
      is given. How can I make the script to stop and, for example, print an
      error message?
      >
      Sorry for the n00b question and thanks
      I'm not exactly sure what you mean. This assumes that you intended the
      contents of the file be piped in from the command line.
      Code:
      import sys
      
      if sys.stdin.isatty():
      print >>sys.stderr, "expected input from stdin"
      sys.exit(1)
      
      sys.stdout.write(sys.stdin.read())
      If you simply want a prompt "Enter a filename:", followed by an error
      if it is not a valid file, I would use something like this:

      Code:
      import sys
      
      filename = raw_input("Enter a filename:")
      
      try:
      f = open(filename)
      except IOError,e:
      print >>sys.stderr, e.strerror, e.filename
      sys.exit(e.errno)
      
      #do stuff with f




      Comment

      • Tartifola

        #4
        Re: No file from stdin


        Hi,

        On May 24, 9:48 am, Tartifola <tartif...@gmai l.comwrote:
        Hi,
        suppose a script of python is waiting for a file from the stdin and none
        is given. How can I make the script to stop and, for example, print an
        error message?

        Sorry for the n00b question and thanks
        >
        I'm not exactly sure what you mean. This assumes that you intended the
        contents of the file be piped in from the command line.
        [code]
        import sys
        >
        if sys.stdin.isatt y():
        print >>sys.stderr, "expected input from stdin"
        sys.exit(1)
        That's exactly what I was looking for. I did not know about isatty()
        thanks

        Comment

        Working...