从 python 中的 rsync 列表命令中删除文件权限、创建日期



我正在使用 rsync --list-only 命令和 Django/Python:

subprocess.Popen(['rsync', '--list-only', source],
                           stdout=subprocess.PIPE, 
                           env={'RSYNC_PASSWORD': password}).communicate()[0]

它返回的结果如下:

drwxrwxrwx 4096 2012/11/07 09:56:23 upload

我不想要所有文件信息。我只想像这样显示文件名:

upload

我该怎么做?谢谢

rsync 没有缩写输出的选项,你需要使用正则表达式(或split()

import re
retval = subprocess.Popen(['rsync', '--list-only', source],
                           stdout=subprocess.PIPE, 
                           env={'RSYNC_PASSWORD': password}).communicate()[0]
retval = re.sub('^.+?d+:d+:d+s+(S+.+)', 'g<1>', retval)

或者(只要文件名没有空格)...

retval = subprocess.Popen(['rsync', '--list-only', source],
                           stdout=subprocess.PIPE, 
                           env={'RSYNC_PASSWORD': password}).communicate()[0]
retval = retval.split(' ')[-1]

您可以将str.splitmaxsplit 参数一起使用,以丢弃前 4 个字段。 例如

>>> "drwxrwxrwx 4096 2012/11/07 09:56:23 upload".split(None, 4)[-1]
'upload'
>>> "drwxrwxrwx 4096 2012/11/07 09:56:23 doc with spaces.txt".split(None, 4)[-1]
'doc with spaces.txt'

None用作分隔符来表示任何空格

在您的情况下,假设您的 rsync 命令可能返回多个文件,您可以尝试:

# retrieve output
out = subprocess.Popen(['rsync', '--list-only', source],
                       stdout=subprocess.PIPE, 
                       env={'RSYNC_PASSWORD': password}).communicate()[0]
# parse block of text into list of strings
lines = (x.strip() for x in out.split('n'))
# take only filenames (ignoring empty lines)
filenames = [x.split(None, 4)[-1] for x in lines if x]

最新更新