Albert
Albert

Reputation: 123

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()

Upvotes: 1

Views: 2697

Answers (3)

fixxxer
fixxxer

Reputation: 16134

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"

Upvotes: 0

Ram
Ram

Reputation: 1115

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()

Upvotes: 0

EvenLisle
EvenLisle

Reputation: 4812

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, i.e. they can point to two distinct (but equal) objects and == will yield True.

Upvotes: 3

Related Questions