简体   繁体   中英

read from stdin python

I am trying to take a filename input from the first command line argument and if there is none then to read from stdin but for some reason my if statement does not seem to be working. I have pasted it below. Any help would be greatly appreciated.

import sys


filename=sys.argv[1]

if filename==None:
   filename=sys.stdin.readlines()

You should check the length of sys.argv before trying to index it:

import sys
if len(sys.argv) > 1:
  filename=sys.argv[1]
else:
  filename=sys.stdin.readline().strip()

The first element in sys.argv is always the filename of the python script, hence the > 1 .

[EDIT]

To expand on fixxxer's answer regarding is vs == :

is returns True if the variables compared point to the same object. This holds true for None , as None is a singleton. == on the other hand, returns True if the variables compared are equal, ie they can point to two distinct (but equal) objects and == will yield True .

Two things:

  1. Like EventLisle says, check for the size of sys.argv before proceeding.
  2. The right way to check if a variable is None is :

    variable is None:

You code could be structured like so:

import sys

if len(sys.argv[1]):
    filename=sys.argv[1]
    # do your thing
else:
    print "list is empty"

I am wondering as per your code the flow would never reached the if block and it would have throw an IndexError exception in line filename=sys.argv[1] , so may be you can try the below code

import sys

try:
   filename=sys.argv[1]
except IndexError: 
   filename=sys.stdin.readlines()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM