Python代码,subprocess与glob一起有效吗?
简单来说,我需要一个程序,可以通过sftp把本地文件夹里的所有txt文件上传到一个特定的远程文件夹。如果我在sftp命令行中已经进入了正确的本地文件夹,运行命令mput *.txt就能达到我的目的。
这是我正在尝试的代码。运行时没有错误,但当我用sftp连接到服务器并查看上传的文件夹时,发现里面是空的。可能我走错方向了。我看到其他解决方案,比如在bash中用lftp的mget命令……但我真的想用python来实现。不管怎样,我还有很多东西需要学习。这是我经过几天阅读一些StackOverflow用户的建议和一些可能有用的库后总结出来的。我不确定能否用subprocess来实现“for i in allfiles:”这个循环。
import os
import glob
import subprocess
os.chdir('/home/submitid/Local/Upload') #change pwd so i can use mget *.txt and glob similarly
pwd = '/Home/submitid/Upload' #remote directory to upload all txt files to
allfiles = glob.glob('*.txt') #get a list of txt files in lpwd
target="user@sftp.com"
sp = subprocess.Popen(['sftp', target], shell=False, stdin=subprocess.PIPE)
sp.stdin.write("chdir %s\n" % pwd) #change directory to pwd
for i in allfiles:
sp.stdin.write("put %s\n" % allfiles) #for each file in allfiles, do a put %filename to pwd
sp.stdin.write("bye\n")
sp.stdin.close()
2 个回答
0
你不需要一个一个地处理allfiles
。
sp.stdin.write("put *.txt\n")
这样就够了。你只需要告诉sftp一次性上传所有文件,而不是一个一个上传。
0
当你遍历 allfiles
时,你并没有传递迭代器变量 sp.stdin.write
,而是直接传递了 allfiles
本身。应该是这样:
for i in allfiles:
sp.stdin.write("put %s\n" % i) #for each file in allfiles, do a put %filename to pwd
你可能还需要等 sftp
验证完身份后再发出命令。你可以从进程中读取标准输出,或者在代码里加一些 time.sleep
的延迟。
不过,为什么不直接使用 scp
呢?你可以构建完整的命令行,然后检查它是否成功执行。像这样:
result = os.system('scp %s %s:%s' % (' '.join(allfiles), target, pwd))
if result != 0:
print 'error!'