0

I have a program that needs input: program.py < test.txt

How would I make it so that the program will exit if it doesn't get a file input?

this is how I read the input:

def file():
    global index
    import sys


    tempo = sys.stdin.readlines()

    for element in tempo:

        if(index == 1):
            key_route.append(element.strip('\n').rstrip().lstrip().lower())
            index = 5
        else:
            routes.append(element.strip('\n').rstrip().lstrip().lower())
Julian
  • 25
  • 6

2 Answers2

0

test if you have anything in temp:

if not temp: 
    exit() 
RickyA
  • 15,465
  • 5
  • 71
  • 95
0

The following should do:

global index
import sys

def file():
    tempo = sys.stdin.readline()

    if not tempo.strip():
        sys.exit()

    for element in tempo:
        if(index == 1):
            key_route.append(element.strip('\n').rstrip().lstrip().lower())
            index = 5
        else:
            routes.append(element.strip('\n').rstrip().lstrip().lower())

file()
  1. Use readline() not readlines()
  2. you need to strip() the var because it will register the '\n' and consider it not empty.
Jackson
  • 1,213
  • 1
  • 4
  • 14