使用 pexpect 调用 rsync:glob 字符串不起作用

Calling rsync with pexpect: glob string not working

我正在尝试 rsync 一些文件 pexpect。我提供的用于识别所有源文件的 glob 字符串参数似乎不起作用。

它的要点是这样的...

import pexpect
import sys

glob_str = (
    "[0-9]" * 4 + "-" +
    "[0-9]" * 2 + "-" +
    "[0-9]" * 2 + "-" +
    "[A-B]" + "*"
)

SRC = "../data/{}".format(glob_str)
DES = "user@host:" + "/path/to/dest/"

args = [
    "-avP",
    SRC,
    DES,
]

print "rsync" + " ".join(args)

# Execute the transfer
child = pexpect.spawn("rsync", args)
child.logfile_read = sys.stdout  # log what the child sends back
child.expect("Password:")
child.sendline("#######")
child.expect(pexpect.EOF)

失败...

building file list ...
rsync: link_stat "/Users/U6020643/git/ue-sme-query-logs/code/../data/[0-9][0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9]\-[A-B]*" failed: No such file or directory (2)
0 files to consider
...

shell 中的相同命令 运行 工作正常

rsync -avP ../data/[0-9][0-9][0-9][0-9]\-[0-9][0-9]\-[0-9][0-9]\-[A-B].csv username@host:/path/to/dest/

pexpect documentation提到这个

Remember that Pexpect does NOT interpret shell meta characters such as redirect, pipe, or wild cards (>, |, or *). This is a common mistake. If you want to run a command and pipe it through another command then you must also start a shell.

但是这样做...

...
args = [
    "rsync",
    "-avP",
    SRC,
    DES,
]
...
child = pexpect.spawn("/bin/bash", args)  # have to use a shell for glob expansion to work
...

遇到权限问题

/usr/bin/rsync: /usr/bin/rsync: cannot execute binary file

要 运行 rsyncbash 你必须使用 bash -c "cmd...":

args = ["-c", "rsync -avP {} {}".format(SRC, DES)]
child = pexpect.spawn('/bin/bash', args=args)

我想你也可以试试 rsync --include=PATTERN