使用pexpect调用rsync:glob string不起作用

时间:2016-10-19 02:14:20

标签: python-2.7 shell glob pexpect

我正在尝试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提及此

  

请记住,Pexpect不会解释shell元字符,例如重定向,管道或外卡(>,|或*)。这是一个常见的错误。如果你想运行一个命令并通过另一个命令传递它,那么你还必须启动一个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

1 个答案:

答案 0 :(得分:1)

要使用rsync运行bash,您必须使用bash -c "cmd..."

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

我认为您也可以尝试rsync --include=PATTERN