简体   繁体   中英

IndexError: list index out of range - Opening file from cli - argv[1]

With this method:

import croniter
import datetime
import re
import time
from sys import argv

now=datetime.datetime.now()

def main():
    filename=open(sys.argv[1])
    f1 = filename.readlines() 
    for x in f1:
        if not re.match('^[0-9*]', x):
            continue
        a = re.split(r'\s+', x)
        cron = croniter.croniter(' '.join(a[:5]), now)
        print("%s %s" % (cron.get_next(datetime.datetime), ' '.join(a[5:])))

if __name__ == "__main__":
    main()

I'm aiming to open a file (a crontab one, provided on stdin), but this line: filename=open(sys.argv[1]) is throwing me this:

Traceback (most recent call last):
File "cron.py", line 25, in <module>
main()
File "cron.py", line 13, in main
filename=open(sys.argv[1])
IndexError: list index out of range

I'm using this script like this: python cron.py < /etc/crontab

I double checked examples given about opening a file in this way, and it just seems to be fine.

Any ideas?

def main():
    filename=open(sys.argv[1])

that would work with python cron.py /etc/crontab .

But instead, you have no arguments, and feeding input using stdin

Change to:

filename = sys.stdin

(and don't close it)

Aside: filename is ill-chosen, since it's a file handle. That adds to the confusion between input stream and input file.

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