By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,089 Members | 2,432 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,089 IT Pros & Developers. It's quick & easy.

No file from stdin

P: n/a


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
May 24 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
On 24 mai, 18:48, Tartifola <tartif...@gmail.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.basename(sys.argv[0]),)
sys.exit(1)

print 'Your filename is %s' % (sys.argv[1],)
May 24 '07 #2

P: n/a
On May 24, 9:48 am, Tartifola <tartif...@gmail.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.
Expand|Select|Wrap|Line Numbers
  1. import sys
  2.  
  3. if sys.stdin.isatty():
  4. print >>sys.stderr, "expected input from stdin"
  5. sys.exit(1)
  6.  
  7. sys.stdout.write(sys.stdin.read())
  8.  
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:

Expand|Select|Wrap|Line Numbers
  1. import sys
  2.  
  3. filename = raw_input("Enter a filename:")
  4.  
  5. try:
  6. f = open(filename)
  7. except IOError,e:
  8. print >>sys.stderr, e.strerror, e.filename
  9. sys.exit(e.errno)
  10.  
  11. #do stuff with f
  12.  


May 24 '07 #3

P: n/a

Hi,

On May 24, 9:48 am, Tartifola <tartif...@gmail.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)
That's exactly what I was looking for. I did not know about isatty()
thanks
May 25 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.