40

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 Commented Aug 21, 2013 at 23:14
  • 2
    In 2017 there is now a pure-python rsync library :: pyrsync (not a wrapper) 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? 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... 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.

Sign up to request clarification or add additional context in comments.

6 Comments

subprocess.call("rsync -Ccavz --delete DJStatic username@website".split()) is slightly more readable and practical to type.
@jolvi if none of your arguments have spaces ...
Use shlex.split(s) instead of regular s.split() to split arguments up as a normal (POSIX) shell would.
@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: 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?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.