您好我已经创建了这个python脚本,但它只运行了一半而不是完全,没有执行Ftp上传的部分,我该如何修复这个脚本?
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()
答案 0 :(得分:0)
问题是您没有退出命令提示符,因此它保持活动状态。
Quickfix:在批处理字符串末尾添加exit
:
batch = b"""\
ping 192.0.2.2 -n 1 -w 1000 > nul
notepad.exe office-data.txt
exit
"""
但似乎你过分复杂了。您想要检查站点是否处于活动状态,所以只需检查ping
的返回码,然后运行系统命令打开文本文件,例如这样(不是最好的但是避免了stdin / stdout hack) :
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)