2016-11-26 39 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'不能触发这样的错误。 –