在我的python脚本上获取“IndexError:list index out of range”

时间:2015-04-17 19:19:16

标签: python bash

我找到了以下程序,并尝试编辑并使其正常工作。我在Python 2.7中使用Kbuntu。运行脚本时出现以下错误:

  

rm:无法删除'Devices_Config_Pull.xls':没有这样的文件或目录   rm:无法删除'Devices_Config_Pull.zip':没有这样的文件或目录   回溯(最近一次调用最后一次):文件" config_pull.py",第17行,   在       connection = sys.argv [1] IndexError:列表索引超出范围

import os,sys,string
sys.path.append('/home/user/python/lib/lib/python')
import pexpect
import xlwt
import credential

os.system('rm Devices_Config_Pull.xls') #This will remove previews created spreadsheet
os.system('rm Devices_Config_Pull.zip') #This will remove previews created zip

list_devices=open('list.txt').readlines() #This will read the list of devices that file is on the same location as the script


email, UID, passwd, enable = credential.cred() #This is a module that I created that will store all of credential
*connection = sys.argv[1]
connection = int(connection)*

 ### If the argument is 1 it will telnet into the devices if the argument is 2 it will ssh into the devices
if connection == 1:
        tunnel = 'telnet '
        conmess = 'telnet'
elif connection == 2:
        tunnel = ('ssh -o StrictHostKeyChecking=no -l ' + UID + ' ')
        conmess = 'SSH'
######## This for loop block. is the loop for telnet/ssh into the devices

wbk = xlwt.Workbook() #Create an excel workbook
font = xlwt.Font() 
font.bold = True
#style = .XFStyle()
style.font = font     < lines omitted>

1 个答案:

答案 0 :(得分:0)

sys.argv需要来自命令行的输入
你无法在文件存在之前将其删除。

import os,sys,string
import pexpect
import xlwt
import credential
sys.path.append('/home/user/python/lib/lib/python')

if os.path.isfile('Devices_Config_Pull.xls'):
    os.system('rm Devices_Config_Pull.xls') #This will remove previews created spreadsheet
if os.path.isfile('Devices_Config_Pull.zip'):   
    os.system('rm Devices_Config_Pull.zip') #This will remove previews created zip

list_devices=open('list.txt').readlines() #This will read the list of devices that file is on the same location as the script


email, UID, passwd, enable = credential.cred() #This is a module that I created that will store all of credential
if len(sys.argv) < 2:
    print('need cmd line parameters')
    exit()
*connection = sys.argv[1]
connection = int(connection)*

 ### If the argument is 1 it will telnet into the devices if the argument is 2 it will ssh into the devices
if connection == 1:
        tunnel = 'telnet '
        conmess = 'telnet'
elif connection == 2:
        tunnel = ('ssh -o StrictHostKeyChecking=no -l ' + UID + ' ')
        conmess = 'SSH'
######## This for loop block. is the loop for telnet/ssh into the devices

wbk = xlwt.Workbook() #Create an excel workbook
font = xlwt.Font() 
font.bold = True
#style = .XFStyle()
style.font = font     < lines omitted>