【问题标题】:Calling rsync with pexpect: glob string not working使用 pexpect 调用 rsync:glob 字符串不起作用
【发布时间】:2016-10-19 02:14:19
【问题描述】:

我正在尝试使用pexpectrsync 一些文件。我提供的用于识别所有源文件的 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

【问题讨论】:

    标签: python-2.7 shell glob pexpect


    【解决方案1】:

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

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

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

    【讨论】:

    • 有没有办法不使用shell?这可能很危险,尤其是当您的输入来自用户时。
    • 如果你不使用 shell 语法,那么你就不必使用 shell。
    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 2017-07-08
    相关资源
    最近更新 更多