2016-11-26 42 views
-1

嗨我已經創建了這個python腳本,但它只能運行一半而不是完全的,Ftp上傳的一部分沒有執行,我該如何解決這個腳本?Python腳本只執行部分

import subprocess 
import time 

cmdline = ["cmd", "/q", "/k", "echo off"] 
cmd = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True) 
batch = b"""\ 
ping 192.0.2.2 -n 1 -w 1000 > nul 
notepad.exe office-data.txt 
""" 
cmd.stdin.write(batch) 
cmd.stdin.flush() # Must include this to ensure data is passed to child process 
result = cmd.stdout.read() 
print(result) 

import ftplib 

sftp = ftplib.FTP('ftp.example.com','userexample','passexample') # Connect 
fp = open('office-data.txt','rb') # file to send 
sftp.storbinary('STOR office-data.txt', fp) # Send the file 

fp.close() # Close file and FTP 
sftp.quit() 
+1

我猜ftp.example.com和那些登錄細節是不合法的,對於初學者 – n1c9

+0

FTP部分是無關緊要的,因爲問題會發生在簡單的'print'上。 –

+0

請勿使用'shell = True';您已經手動運行cmd.exe。像cmd期望的那樣用'「\ r \ n」'結尾每行,或者用'str'輸入使用'universal_newlines = True'。使用'bufsize = 0'來避免'flush',並避免使用'result,err = cmd.communicate(batch)'造成的死鎖。 – eryksun

回答

0

問題是,您不會退出命令提示符,因此它保持活動狀態。

的QuickFix:在您的批處理字符串末尾添加exit

batch = b"""\ 
ping 192.0.2.2 -n 1 -w 1000 > nul 
notepad.exe office-data.txt 
exit 
""" 

但似乎你過於複雜的事情。你想檢查網站是否存在,所以只需從ping檢查返回代碼,然後運行系統命令打開你的文本文件,例如像這樣(不是最好的但是避免stdin/stdout破解):

cmd = subprocess.Popen("ping 192.0.2.2 -n 1 -w 1000", stdout=subprocess.DEVNULL) 
rc=cmd.wait() 
if rc: 
    raise Exception("Cannot ping site") 
txtfile = "office-data.txt" 
os.system("notepad "+txtfile) 
+0

不工作如何?爲我工作。 –

+0

和?某處有錯誤嗎? –

+0

你在其他地方犯了一個錯誤。向你的字符串添加'exit'不能觸發這樣的錯誤。 –