calling rsync from python subprocess.call

前端 未结 1 2012
温柔的废话
温柔的废话 2021-02-19 04:43

I\'m trying to execute rsync over ssh from a subprocess in a python script to copy images from one server to another. I have a function defined as:

def rsyncBoo         


        
1条回答
  •  不思量自难忘°
    2021-02-19 04:53

    Figured out my issues. My problems were the result of my misunderstanding of how the subprocess.call function executes and bash's expansion of lists inside curly braces.

    When I was issuing the rsync command in a bash shell with subdirectories in curly braces, bash was really expanding that into multiple arguments which were being passed to rsync (/shared/books/book_1 shared/books/book_2, etc.). When passing the same string with curly braces "/shared/books/{book_1, book_2}" to the subprocess.call function, the expansion wasn't happening, since it wasn't going through bash, so my argument to rsync was really "/shared/books/{book_1, book_2}".

    Similarly, the single quotes around the file patterns ('*', '*.jpg', etc.) work on the bash command line (only the values inside the single quotes are passed to rsync), but inside subprocess.call, the single quotes are passed to rsync as the file pattern ("'*.jpg'").

    New (working) code looks like this:

    def rsyncBookContent(bookIds, serverEnv):
        bookPaths = []
        for b in bookIds:
            bookPaths.append(options.bookDestDir + "/book_" + str(b))
        args = []
        for host in serverEnv['content.hosts']:
            # copy all *.jpg files via ssh
            args = ["rsync", "-avz", "--include", "*/", "--include", "*.jpg", "--exclude", "*", "-e", "ssh"]
            args.extend(bookPaths)
            args.append("jill@" + host + ":/home/jill/web/public/static/"])
            print "executing " + ' '.join(args)
            subprocess.call(args)
    

    0 讨论(0)
提交回复
热议问题