Get output continuously: rsync info=progress2 call in python scriptread subprocess stdout line by lineHow can I do a line break (line continuation) in Python?Terminating a Python scriptCalling an external command in PythonHow to get the current time in PythonHow can you profile a Python script?How to get line count cheaply in Python?Getting the last element of a list in PythonHow do I check what version of Python is running my script?How do I get the number of elements in a list in Python?Why do people write the #!/usr/bin/env python shebang on the first line of a Python script?

What is the tangent at a sharp point on a curve?

Why didn't Voldemort know what Grindelwald looked like?

What is the period/term used describe Giuseppe Arcimboldo's style of painting?

Would this string work as string?

Started in 1987 vs. Starting in 1987

Strange behavior in TikZ draw command

Can you take a "free object interaction" while incapacitated?

Taking the numerator and the denominator

Pre-Employment Background Check With Consent For Future Checks

Magnifying glass in hyperbolic space

Why can't I get pgrep output right to variable on bash script?

Unfrosted light bulb

If the Dominion rule using their Jem'Hadar troops, why is their life expectancy so low?

Output visual diagram of picture

What is it called when someone votes for an option that's not their first choice?

Why does the frost depth increase when the surface temperature warms up?

Sort with assumptions

Should a narrator ever describe things based on a character's view instead of facts?

New Order #2: Turn My Way

What is the purpose of using a decision tree?

Would a primitive species be able to learn English from reading books alone?

What properties make a magic weapon befit a Rogue more than a DEX-based Fighter?

Do I have to take mana from my deck or hand when tapping this card?

I keep switching characters, how do I stop?



Get output continuously: rsync info=progress2 call in python script


read subprocess stdout line by lineHow can I do a line break (line continuation) in Python?Terminating a Python scriptCalling an external command in PythonHow to get the current time in PythonHow can you profile a Python script?How to get line count cheaply in Python?Getting the last element of a list in PythonHow do I check what version of Python is running my script?How do I get the number of elements in a list in Python?Why do people write the #!/usr/bin/env python shebang on the first line of a Python script?













-1















I'm calling rsync with popen and the output is not printing out continuously in my python script for my web application as it does in just normal linux. I'm trying to copy over all the files on one directory to another (massive copy). I want to use the progress numbers received from the output changing to eventually create/update a progress-bar I have in my web application. All I want is the total progress of the overall copy so I would use --info=progress2 in my rsync command.
I also tried :



while True:
line = self.proc.stdout.readline()
if line != '':
# the real code does filtering here
print("test:", line.rstrip())
else:
break


but that waited till the end to just print test: b''
I think the issues is either with the while loop extracting data or how I print it to my console using a different class too.



There is not much information of using this --info=progress2
since it's a relatively new update.



Here's my code.



import subprocess
import logging
import sys
import os
import replicator.dfp.rep_utils as ru


class SyncProcessor(object):
def __init__(self, src, dest):
self.src = src
self.dest = dest
self.proc = None
self.callback = None
log_file = "sync--.log".format(self.src, self.dest)
self.sync_logger = ru.setup_logger(__file__, log_file, level=logging.DEBUG)

def add_sync_callback(self, cb):
self.callback = cb

def run(self):
print("Syncing Drive "+ str(self.src.driveNum) + " to Drive " + str(self.dest.driveNum))
rsync_cmd = "sudo rsync -ah --info=progress2 --delete --stats /media/drive/ /media/drive".format(self.src.driveNum, self.dest.driveNum)
self.proc = subprocess.Popen(rsync_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while self.proc.poll() is None:
output = self.proc.stdout.readline()
if output == '':
break
if output:
print("OUTPUT DECODE: " + output.decode("utf-8")
#self.sync_logger.info(output.decode())
self.callback.update(output.decode())
print("<< Finished Syncing >>")
#self.sync_logger.debug("<< Finished Syncing >>")
rc = self.proc.poll()
#self.sync_logger.debug("Return code: ".format(rc))
os.system("sync")
return rc

def communicate(self):
return self.proc.communicate()

class Progress(object):
"""Callback to report progress of a SyncProcessor"""
def __init__(self, src, dest, out=sys.stdout):
self.src = src
self.dest = dest
self.out = out

def update(self, data):
line = "From Progress(-) -> "
self.out.write(line.format(self.src, self.dest, data))









share|improve this question
























  • Possible duplicate of read subprocess stdout line by line

    – gdlmx
    Mar 7 at 20:39















-1















I'm calling rsync with popen and the output is not printing out continuously in my python script for my web application as it does in just normal linux. I'm trying to copy over all the files on one directory to another (massive copy). I want to use the progress numbers received from the output changing to eventually create/update a progress-bar I have in my web application. All I want is the total progress of the overall copy so I would use --info=progress2 in my rsync command.
I also tried :



while True:
line = self.proc.stdout.readline()
if line != '':
# the real code does filtering here
print("test:", line.rstrip())
else:
break


but that waited till the end to just print test: b''
I think the issues is either with the while loop extracting data or how I print it to my console using a different class too.



There is not much information of using this --info=progress2
since it's a relatively new update.



Here's my code.



import subprocess
import logging
import sys
import os
import replicator.dfp.rep_utils as ru


class SyncProcessor(object):
def __init__(self, src, dest):
self.src = src
self.dest = dest
self.proc = None
self.callback = None
log_file = "sync--.log".format(self.src, self.dest)
self.sync_logger = ru.setup_logger(__file__, log_file, level=logging.DEBUG)

def add_sync_callback(self, cb):
self.callback = cb

def run(self):
print("Syncing Drive "+ str(self.src.driveNum) + " to Drive " + str(self.dest.driveNum))
rsync_cmd = "sudo rsync -ah --info=progress2 --delete --stats /media/drive/ /media/drive".format(self.src.driveNum, self.dest.driveNum)
self.proc = subprocess.Popen(rsync_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while self.proc.poll() is None:
output = self.proc.stdout.readline()
if output == '':
break
if output:
print("OUTPUT DECODE: " + output.decode("utf-8")
#self.sync_logger.info(output.decode())
self.callback.update(output.decode())
print("<< Finished Syncing >>")
#self.sync_logger.debug("<< Finished Syncing >>")
rc = self.proc.poll()
#self.sync_logger.debug("Return code: ".format(rc))
os.system("sync")
return rc

def communicate(self):
return self.proc.communicate()

class Progress(object):
"""Callback to report progress of a SyncProcessor"""
def __init__(self, src, dest, out=sys.stdout):
self.src = src
self.dest = dest
self.out = out

def update(self, data):
line = "From Progress(-) -> "
self.out.write(line.format(self.src, self.dest, data))









share|improve this question
























  • Possible duplicate of read subprocess stdout line by line

    – gdlmx
    Mar 7 at 20:39













-1












-1








-1








I'm calling rsync with popen and the output is not printing out continuously in my python script for my web application as it does in just normal linux. I'm trying to copy over all the files on one directory to another (massive copy). I want to use the progress numbers received from the output changing to eventually create/update a progress-bar I have in my web application. All I want is the total progress of the overall copy so I would use --info=progress2 in my rsync command.
I also tried :



while True:
line = self.proc.stdout.readline()
if line != '':
# the real code does filtering here
print("test:", line.rstrip())
else:
break


but that waited till the end to just print test: b''
I think the issues is either with the while loop extracting data or how I print it to my console using a different class too.



There is not much information of using this --info=progress2
since it's a relatively new update.



Here's my code.



import subprocess
import logging
import sys
import os
import replicator.dfp.rep_utils as ru


class SyncProcessor(object):
def __init__(self, src, dest):
self.src = src
self.dest = dest
self.proc = None
self.callback = None
log_file = "sync--.log".format(self.src, self.dest)
self.sync_logger = ru.setup_logger(__file__, log_file, level=logging.DEBUG)

def add_sync_callback(self, cb):
self.callback = cb

def run(self):
print("Syncing Drive "+ str(self.src.driveNum) + " to Drive " + str(self.dest.driveNum))
rsync_cmd = "sudo rsync -ah --info=progress2 --delete --stats /media/drive/ /media/drive".format(self.src.driveNum, self.dest.driveNum)
self.proc = subprocess.Popen(rsync_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while self.proc.poll() is None:
output = self.proc.stdout.readline()
if output == '':
break
if output:
print("OUTPUT DECODE: " + output.decode("utf-8")
#self.sync_logger.info(output.decode())
self.callback.update(output.decode())
print("<< Finished Syncing >>")
#self.sync_logger.debug("<< Finished Syncing >>")
rc = self.proc.poll()
#self.sync_logger.debug("Return code: ".format(rc))
os.system("sync")
return rc

def communicate(self):
return self.proc.communicate()

class Progress(object):
"""Callback to report progress of a SyncProcessor"""
def __init__(self, src, dest, out=sys.stdout):
self.src = src
self.dest = dest
self.out = out

def update(self, data):
line = "From Progress(-) -> "
self.out.write(line.format(self.src, self.dest, data))









share|improve this question
















I'm calling rsync with popen and the output is not printing out continuously in my python script for my web application as it does in just normal linux. I'm trying to copy over all the files on one directory to another (massive copy). I want to use the progress numbers received from the output changing to eventually create/update a progress-bar I have in my web application. All I want is the total progress of the overall copy so I would use --info=progress2 in my rsync command.
I also tried :



while True:
line = self.proc.stdout.readline()
if line != '':
# the real code does filtering here
print("test:", line.rstrip())
else:
break


but that waited till the end to just print test: b''
I think the issues is either with the while loop extracting data or how I print it to my console using a different class too.



There is not much information of using this --info=progress2
since it's a relatively new update.



Here's my code.



import subprocess
import logging
import sys
import os
import replicator.dfp.rep_utils as ru


class SyncProcessor(object):
def __init__(self, src, dest):
self.src = src
self.dest = dest
self.proc = None
self.callback = None
log_file = "sync--.log".format(self.src, self.dest)
self.sync_logger = ru.setup_logger(__file__, log_file, level=logging.DEBUG)

def add_sync_callback(self, cb):
self.callback = cb

def run(self):
print("Syncing Drive "+ str(self.src.driveNum) + " to Drive " + str(self.dest.driveNum))
rsync_cmd = "sudo rsync -ah --info=progress2 --delete --stats /media/drive/ /media/drive".format(self.src.driveNum, self.dest.driveNum)
self.proc = subprocess.Popen(rsync_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

while self.proc.poll() is None:
output = self.proc.stdout.readline()
if output == '':
break
if output:
print("OUTPUT DECODE: " + output.decode("utf-8")
#self.sync_logger.info(output.decode())
self.callback.update(output.decode())
print("<< Finished Syncing >>")
#self.sync_logger.debug("<< Finished Syncing >>")
rc = self.proc.poll()
#self.sync_logger.debug("Return code: ".format(rc))
os.system("sync")
return rc

def communicate(self):
return self.proc.communicate()

class Progress(object):
"""Callback to report progress of a SyncProcessor"""
def __init__(self, src, dest, out=sys.stdout):
self.src = src
self.dest = dest
self.out = out

def update(self, data):
line = "From Progress(-) -> "
self.out.write(line.format(self.src, self.dest, data))






python linux subprocess rsync popen






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 11 at 12:24







kenedy

















asked Mar 7 at 20:15









kenedykenedy

11




11












  • Possible duplicate of read subprocess stdout line by line

    – gdlmx
    Mar 7 at 20:39

















  • Possible duplicate of read subprocess stdout line by line

    – gdlmx
    Mar 7 at 20:39
















Possible duplicate of read subprocess stdout line by line

– gdlmx
Mar 7 at 20:39





Possible duplicate of read subprocess stdout line by line

– gdlmx
Mar 7 at 20:39












1 Answer
1






active

oldest

votes


















0














So what I realized was the whole changing of percent from 0-100% was treated as one line since it was broken up by r instead of n



self.proc.stdout.readline()



therefore this line only activates after process reaches 100%



I switched it to self.proc.stdout.readline(80)
which worked as it printed out every 80 characters giving me updates on the precentage. However since length of line changes throughout I'm looking for a better way to do this






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55052122%2fget-output-continuously-rsync-info-progress2-call-in-python-script%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    So what I realized was the whole changing of percent from 0-100% was treated as one line since it was broken up by r instead of n



    self.proc.stdout.readline()



    therefore this line only activates after process reaches 100%



    I switched it to self.proc.stdout.readline(80)
    which worked as it printed out every 80 characters giving me updates on the precentage. However since length of line changes throughout I'm looking for a better way to do this






    share|improve this answer



























      0














      So what I realized was the whole changing of percent from 0-100% was treated as one line since it was broken up by r instead of n



      self.proc.stdout.readline()



      therefore this line only activates after process reaches 100%



      I switched it to self.proc.stdout.readline(80)
      which worked as it printed out every 80 characters giving me updates on the precentage. However since length of line changes throughout I'm looking for a better way to do this






      share|improve this answer

























        0












        0








        0







        So what I realized was the whole changing of percent from 0-100% was treated as one line since it was broken up by r instead of n



        self.proc.stdout.readline()



        therefore this line only activates after process reaches 100%



        I switched it to self.proc.stdout.readline(80)
        which worked as it printed out every 80 characters giving me updates on the precentage. However since length of line changes throughout I'm looking for a better way to do this






        share|improve this answer













        So what I realized was the whole changing of percent from 0-100% was treated as one line since it was broken up by r instead of n



        self.proc.stdout.readline()



        therefore this line only activates after process reaches 100%



        I switched it to self.proc.stdout.readline(80)
        which worked as it printed out every 80 characters giving me updates on the precentage. However since length of line changes throughout I'm looking for a better way to do this







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 11 at 17:11









        kenedykenedy

        11




        11





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55052122%2fget-output-continuously-rsync-info-progress2-call-in-python-script%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme