39

I need to run an rsync command from Python. Is this possible and if so, how do I do it?

rsync -Ccavz --delete DJStatic username@website
4
  • 3
    you can run shell commands from python docs.python.org/2/library/subprocess.html, also fabric provides a nice api that wraps many comman shell commands docs.fabfile.org/en/1.4.0/index.html
    – dm03514
    Commented Aug 21, 2013 at 23:14
  • 2
    In 2017 there is now a pure-python rsync library :: pyrsync (not a wrapper)
    – philshem
    Commented Feb 17, 2017 at 22:08
  • 1
    @philshem: It seems that repo hasn't been updated since 2013. What advantage does it offer vs. the system call?
    – Bryan P
    Commented Apr 13, 2021 at 23:07
  • I have written a very basic wrapper using system's rsync and pythons subprocess, providing some features like printing the progress etc for my own personal purposes: github.com/lfreist/PyRsync...
    – prog2de
    Commented Jan 10, 2022 at 22:08

1 Answer 1

31

You can call a subprocess from python using the following snippet

import subprocess
subprocess.call(["ls", "-l"])

In your case, it would be something like this

subprocess.call(["rsync", "-Ccavz", "--delete","DJStatic", "username@website"])

See here for more details.

6
  • 8
    subprocess.call("rsync -Ccavz --delete DJStatic username@website".split()) is slightly more readable and practical to type.
    – jolvi
    Commented Jun 9, 2017 at 14:51
  • 15
    @jolvi if none of your arguments have spaces ...
    – blueFast
    Commented Feb 18, 2019 at 8:23
  • 6
    Use shlex.split(s) instead of regular s.split() to split arguments up as a normal (POSIX) shell would. Commented Mar 27, 2020 at 17:02
  • 2
    @jolvi's version (passing command as string) should not be used! Pass the arguments as a list of strings. It will save you tons of time debugging later on when you can't figure out why your shell command isn't doing what you expect due to some quotes or spaces in a variable somewhere. The tradeoff of saving 2-3 seconds of typing just isn't worth it
    – Brandon
    Commented Oct 9, 2020 at 19:17
  • @Brandon: For those who don't have spaces in the command, that's totally fine, and it is easier. If there are spaces, that approach can be fixed using shlex.split() instead of split(), as mentioned by Chris L. Barnes. I think it's fine to use that solution if you do so cautiously. Unless...is there some other specific issue this causes?
    – jvriesem
    Commented Aug 20, 2021 at 20:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.