2016-01-20 46 views
0

我正在用getopt編寫一個ftp上傳器。如果使用fullname = 'file.jpg'全部是好的,但如果不fullname = newfiles轉身返回錯誤通知:Python ftp上傳bug:沒有屬性'rfind'

AttributeError: 'list' object has no attribute 'rfind'

也許我的應用程序沒有權限發送的文件嗎?

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import sys 
import getopt 
import ftplib 
import os 

def usage(): 
    print "Home" 
#if __name__ == "__main__": 
try: 
    opts, args = getopt.getopt(sys.argv[1:], "uhc", ["upload=", "help", "connect"]) 
except getopt.GetoptError: 
    usage() 
    sys.exit(2) 


if opts == []: 
    usage() 

for opt, arg in opts: 
    if opt in ("-h", "--help"): 
     usage() 
    elif opt in ("-u", "--upload"): 
     newfile = args 
     if not file: 
      print "Nie wybrano pliku!" 
     else: 
      print "Wybrany plik",newfile 
      ftp = ftplib.FTP() 
      ftp.connect('host') 
      ftp.login('user', 'pass') 
      ftp.cwd('./') 
      print "Wybieram:", ftp.pwd() 
      print "Wgrywam" 
      fullname = newfile 
      name = os.path.split(fullname)[1] 
      f = open(fullname, "rb") 
      ftp.storbinary('STOR ' + name, f) 
      f.close() 
      print "OK" 

      print "Files:" 
      print ftp.retrlines('LIST') 
      ftp.quit() 
    elif opt in ("-c", "--connect"): 
     print "a" 

回答

1

我認爲您的腳本可以使用一些修改。該錯誤是由於將一個列表傳遞給os.path.split()函數。

我建議如下:

按照getopt機制的文檔,需要一個參數應遵循一個冒號選項「:」。

改變這一行:

opts, args = getopt.getopt(sys.argv[1:], "uhc", ["upload=", "help", "connect"]) 

爲了這個(在你的選擇列表中的U後加冒號):

opts, args = getopt.getopt(sys.argv[1:], "u:hc", ["upload=", "help", "connect"]) 

然後在你的for循環中,ARG變量將被填充電影名稱。設置newfile = arg而不是args。

更改此:

elif opt in ("-u", "--upload"): 
     newfile = args 

對此(ARG而不是參數):

elif opt in ("-u", "--upload"): 
     newfile = arg 

更改後,你應該能夠有1個或多個文件,運行腳本,例如: your_script.py -u 「file1.jpg」 -U 「file2.jpg」

而且,下面的代碼:

if not file: 
     print "Nie wybrano pliku!" 
    else: 
     print "Wybrany plik",newfile 

本例中的「文件」是一個python內建函數,應該始終落入else條件。另一個選項可能是使用os.path.isfile(newfile)檢查文件的存在。

+0

如果改變UHC到u:HC不會轉向我,如果 如果沒有文件: 「聶wybrano pliku」 \t \t \t打印 \t \t其他: \t \t \t打印 「Wybrany plik」,文件 如果空視圖的使用(),爲什麼? – Grz3siu

+0

請以您如何致電您的劇本爲例進行評論。我編輯了我的答案來嘗試和幫助。您的「if note file:」語句是否仍然與您問題中的當前代碼相匹配,或者它是否已經更改? – robdjc