Watching something be written to a file live with tailRedirect output of remote python app started through ssh to fileUbuntu RFID Screensaver lock-unlockHow can I offer an XP-compatible migration to Linux Mint?Is there a command in Linux which waits till it will be terminated?Ctrl+c in a sub process is killing a nohup'ed process earlier in the scripthow to get cronjob running every minuteCtrl-C'd an in-place recursive gzip - is this likely to have broken anything?Getting output of another script while preserving line-breakssocat and rich terminal again“Ctrl + c” combination works different on different SSH clients

Did converts (ger tzedek) in ancient Israel own land?

What is the intuition behind short exact sequences of groups; in particular, what is the intuition behind group extensions?

Why does Kotter return in Welcome Back Kotter

Stopping power of mountain vs road bike

Do I have a twin with permutated remainders?

Is there a hemisphere-neutral way of specifying a season?

Etiquette around loan refinance - decision is going to cost first broker a lot of money

Emailing HOD to enhance faculty application

What is the word for reserving something for yourself before others do?

In a Spin are Both Wings Stalled?

What is the PIE reconstruction for word-initial alpha with rough breathing?

Facing a paradox: Earnshaw's theorem in one dimension

SSH "lag" in LAN on some machines, mixed distros

Arrow those variables!

Why is the 'in' operator throwing an error with a string literal instead of logging false?

Does casting Light, or a similar spell, have any effect when the caster is swallowed by a monster?

Brothers & sisters

Is it inappropriate for a student to attend their mentor's dissertation defense?

How badly should I try to prevent a user from XSSing themselves?

How do I write bicross product symbols in latex?

What is going on with Captain Marvel's blood colour?

Took a trip to a parallel universe, need help deciphering

A reference to a well-known characterization of scattered compact spaces

Will google still index a page if I use a $_SESSION variable?



Watching something be written to a file live with tail


Redirect output of remote python app started through ssh to fileUbuntu RFID Screensaver lock-unlockHow can I offer an XP-compatible migration to Linux Mint?Is there a command in Linux which waits till it will be terminated?Ctrl+c in a sub process is killing a nohup'ed process earlier in the scripthow to get cronjob running every minuteCtrl-C'd an in-place recursive gzip - is this likely to have broken anything?Getting output of another script while preserving line-breakssocat and rich terminal again“Ctrl + c” combination works different on different SSH clients






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








21















I have a python program which is, slowly, generating some output.



I want to capture that in a file, but I also thought I could watch it live with tail.



So in one terminal I'm doing :



python myprog.py > output.txt


and in another terminal :



tail -f output.txt


But it seems like the tail isn't showing me anything while the python program is running.



If I hit ctrl-c to kill the python script, suddenly the tail of output.txt starts filling up. But not while python is running.



What am I doing wrong?










share|improve this question



















  • 9





    How about python myprog.py | tee output.txt instead?

    – n8te
    yesterday






  • 3





    @n8te tee might show the same problem if the program isn't flushing the output buffer regularly. This needs flush() and tee.

    – JPhi1618
    22 hours ago






  • 1





    stdbuf can be used to alter the buffering status of file descriptors.

    – studog
    6 hours ago











  • Terminology: There is no pipe anywhere in this scenario. There's a redirect to a regular file. (Which causes C stdio and Python to decide to make stdout full-buffered instead of line-buffered because it's not a TTY). Pipes are a different type of file (a buffer inside the kernel). I edited your question to correct that.

    – Peter Cordes
    5 hours ago












  • Probably not needed in your situation but if you don't want to terminate the program you can use gdb and call fflush: see stackoverflow.com/questions/8251269/…

    – Mark Wagner
    5 hours ago

















21















I have a python program which is, slowly, generating some output.



I want to capture that in a file, but I also thought I could watch it live with tail.



So in one terminal I'm doing :



python myprog.py > output.txt


and in another terminal :



tail -f output.txt


But it seems like the tail isn't showing me anything while the python program is running.



If I hit ctrl-c to kill the python script, suddenly the tail of output.txt starts filling up. But not while python is running.



What am I doing wrong?










share|improve this question



















  • 9





    How about python myprog.py | tee output.txt instead?

    – n8te
    yesterday






  • 3





    @n8te tee might show the same problem if the program isn't flushing the output buffer regularly. This needs flush() and tee.

    – JPhi1618
    22 hours ago






  • 1





    stdbuf can be used to alter the buffering status of file descriptors.

    – studog
    6 hours ago











  • Terminology: There is no pipe anywhere in this scenario. There's a redirect to a regular file. (Which causes C stdio and Python to decide to make stdout full-buffered instead of line-buffered because it's not a TTY). Pipes are a different type of file (a buffer inside the kernel). I edited your question to correct that.

    – Peter Cordes
    5 hours ago












  • Probably not needed in your situation but if you don't want to terminate the program you can use gdb and call fflush: see stackoverflow.com/questions/8251269/…

    – Mark Wagner
    5 hours ago













21












21








21


1






I have a python program which is, slowly, generating some output.



I want to capture that in a file, but I also thought I could watch it live with tail.



So in one terminal I'm doing :



python myprog.py > output.txt


and in another terminal :



tail -f output.txt


But it seems like the tail isn't showing me anything while the python program is running.



If I hit ctrl-c to kill the python script, suddenly the tail of output.txt starts filling up. But not while python is running.



What am I doing wrong?










share|improve this question
















I have a python program which is, slowly, generating some output.



I want to capture that in a file, but I also thought I could watch it live with tail.



So in one terminal I'm doing :



python myprog.py > output.txt


and in another terminal :



tail -f output.txt


But it seems like the tail isn't showing me anything while the python program is running.



If I hit ctrl-c to kill the python script, suddenly the tail of output.txt starts filling up. But not while python is running.



What am I doing wrong?







linux command-line redirection stdout






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 5 hours ago









Peter Cordes

2,4751621




2,4751621










asked yesterday









interstarinterstar

415413




415413







  • 9





    How about python myprog.py | tee output.txt instead?

    – n8te
    yesterday






  • 3





    @n8te tee might show the same problem if the program isn't flushing the output buffer regularly. This needs flush() and tee.

    – JPhi1618
    22 hours ago






  • 1





    stdbuf can be used to alter the buffering status of file descriptors.

    – studog
    6 hours ago











  • Terminology: There is no pipe anywhere in this scenario. There's a redirect to a regular file. (Which causes C stdio and Python to decide to make stdout full-buffered instead of line-buffered because it's not a TTY). Pipes are a different type of file (a buffer inside the kernel). I edited your question to correct that.

    – Peter Cordes
    5 hours ago












  • Probably not needed in your situation but if you don't want to terminate the program you can use gdb and call fflush: see stackoverflow.com/questions/8251269/…

    – Mark Wagner
    5 hours ago












  • 9





    How about python myprog.py | tee output.txt instead?

    – n8te
    yesterday






  • 3





    @n8te tee might show the same problem if the program isn't flushing the output buffer regularly. This needs flush() and tee.

    – JPhi1618
    22 hours ago






  • 1





    stdbuf can be used to alter the buffering status of file descriptors.

    – studog
    6 hours ago











  • Terminology: There is no pipe anywhere in this scenario. There's a redirect to a regular file. (Which causes C stdio and Python to decide to make stdout full-buffered instead of line-buffered because it's not a TTY). Pipes are a different type of file (a buffer inside the kernel). I edited your question to correct that.

    – Peter Cordes
    5 hours ago












  • Probably not needed in your situation but if you don't want to terminate the program you can use gdb and call fflush: see stackoverflow.com/questions/8251269/…

    – Mark Wagner
    5 hours ago







9




9





How about python myprog.py | tee output.txt instead?

– n8te
yesterday





How about python myprog.py | tee output.txt instead?

– n8te
yesterday




3




3





@n8te tee might show the same problem if the program isn't flushing the output buffer regularly. This needs flush() and tee.

– JPhi1618
22 hours ago





@n8te tee might show the same problem if the program isn't flushing the output buffer regularly. This needs flush() and tee.

– JPhi1618
22 hours ago




1




1





stdbuf can be used to alter the buffering status of file descriptors.

– studog
6 hours ago





stdbuf can be used to alter the buffering status of file descriptors.

– studog
6 hours ago













Terminology: There is no pipe anywhere in this scenario. There's a redirect to a regular file. (Which causes C stdio and Python to decide to make stdout full-buffered instead of line-buffered because it's not a TTY). Pipes are a different type of file (a buffer inside the kernel). I edited your question to correct that.

– Peter Cordes
5 hours ago






Terminology: There is no pipe anywhere in this scenario. There's a redirect to a regular file. (Which causes C stdio and Python to decide to make stdout full-buffered instead of line-buffered because it's not a TTY). Pipes are a different type of file (a buffer inside the kernel). I edited your question to correct that.

– Peter Cordes
5 hours ago














Probably not needed in your situation but if you don't want to terminate the program you can use gdb and call fflush: see stackoverflow.com/questions/8251269/…

– Mark Wagner
5 hours ago





Probably not needed in your situation but if you don't want to terminate the program you can use gdb and call fflush: see stackoverflow.com/questions/8251269/…

– Mark Wagner
5 hours ago










5 Answers
5






active

oldest

votes


















29














You may also need to explicitly flush the buffer for it to get piped upon generation. This is because output is typically only printed when the pipe's buffer fills up (which is in kilobytes I belive), and when the stdin message ends. This is probably to save on read/writes. You could do this after every print, or if you are looping, after the last print within the loop.



import sys
...
print('Some message')
sys.stdout.flush()





share|improve this answer










New contributor




Davey is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 4





    If you have read this far, please don't be thinking of closing and re-opening the file to do this, the seeks will be a problem, especially for very large files. (I've seen this done!).

    – mckenzm
    21 hours ago






  • 2





    You can also use print's flush parameter to do just as well. For example, print('some message', flush=True).

    – Dan
    12 hours ago







  • 4





    It has nothing to do with the pipe's buffer, but with the stdout mechanism which doesn't flush after newline if it doesn't write to a tty.

    – glglgl
    11 hours ago


















18














Instead of trying to tail a live file, use tee instead. It was made to do exactly what you're trying to do.



From man tee:




tee(1) - Linux man page



Name tee - read from standard input and write to standard output and files



Synopsis



tee [OPTION]... [FILE]...


Description



Copy standard input to each FILE, and also to standard output.



-a, --append 
append to the given FILEs, do not overwrite
-i, --ignore-interrupts
ignore interrupt signals
--help
display this help and exit
--version
output version information and exit


If a FILE is -, copy again to standard output.




So in your case you'd run:



python myprog.py | tee output.txt


EDIT: As others have pointed out, this answer will run into the same issue OP was originally having unless sys.stdout.flush() is used in the python program as described in Davey's accepted answer. The testing I did before posting this answer did not accurately reflect OP's use-case.



tee can still be used as an alternative--albeit less than optimal--method of displaying the output while also writing to the file, but Davey's answer is clearly the correct and best answer.






share|improve this answer

























  • tail in another thread is a good solution for when you've started the application before you decide you want to see the output though.

    – Baldrickk
    17 hours ago






  • 7





    That requires a permanent console session, this is why it’s often much easier to use tail -F or even better the follow function of less. But in all cases the flush should be used.

    – eckes
    15 hours ago






  • 3





    This won't solve the problem that the OP is having. Python's output to the pipe will be buffered just like output to the file.

    – Barmar
    7 hours ago


















7














Run python with the unbuffered flag:



python -u myprog.py > output.txt


Output will then print in real time.






share|improve this answer








New contributor




BHC is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.



























    3














    Terminology: There is no pipe anywhere in this scenario. (I edited the question to fix that). Pipes are a different type of file (a buffer inside the kernel).



    This is a redirect to a regular file.



    C stdio, and Python, default to making stdout line-buffered when it's connected to a TTY, otherwise it's full-buffered. Line-buffered means the buffer is flushed after a newline. Full-buffered means it's only flushed to become visible to the OS (i.e. with a write() system call) when it's full.



    You will see output eventually, in chunks of maybe 4kiB at a time. (I don't know the default buffer size.) This is generally more efficient, and means fewer writes to your actual disk. But not great for interactive monitoring, because output is hidden inside the memory of the writing process until it's flushed.



    On Stack Overflow, there's a Disable output buffering Python Q&A which lists many ways to get unbuffered (or line-buffered?) output to stdout in Python. The question itself summarizes the answers.



    Options include running python -u (Or I guess putting #!/usr/bin/python -u at the top of your script), or using the PYTHONUNBUFFERED environment variable for that program. Or explicit flushing after some/all print functions, like @Davey's answer suggests.




    Some other programs have similar options, e.g. GNU grep has --line-buffered, and GNU sed has -u / --unbuffered, for use-cases like this, or for example piping the output of your python program. e.g. ./slowly-output-stuff | grep --line-buffered 'foo.*bar'.






    share|improve this answer






























      0














      Another option (if you don't care about the contents, just the progress) is pv:



      NAME
      pv - monitor the progress of data through a pipe

      SYNOPSIS
      pv [OPTION] [FILE]...
      pv [-h|-V]


      Introduce this in your pipeline and it will show you the number of bytes processed as well as the speed they go through the pipeline.



      If the content is what you actually want to monitor, then tee is the best choice, as the other answer indicates.






      share|improve this answer


















      • 1





        There's no pipeline, just file redirection. And it won't solve the buffering problem.

        – Barmar
        6 hours ago











      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "3"
      ;
      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%2fsuperuser.com%2fquestions%2f1421123%2fwatching-something-be-written-to-a-file-live-with-tail%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      29














      You may also need to explicitly flush the buffer for it to get piped upon generation. This is because output is typically only printed when the pipe's buffer fills up (which is in kilobytes I belive), and when the stdin message ends. This is probably to save on read/writes. You could do this after every print, or if you are looping, after the last print within the loop.



      import sys
      ...
      print('Some message')
      sys.stdout.flush()





      share|improve this answer










      New contributor




      Davey is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.















      • 4





        If you have read this far, please don't be thinking of closing and re-opening the file to do this, the seeks will be a problem, especially for very large files. (I've seen this done!).

        – mckenzm
        21 hours ago






      • 2





        You can also use print's flush parameter to do just as well. For example, print('some message', flush=True).

        – Dan
        12 hours ago







      • 4





        It has nothing to do with the pipe's buffer, but with the stdout mechanism which doesn't flush after newline if it doesn't write to a tty.

        – glglgl
        11 hours ago















      29














      You may also need to explicitly flush the buffer for it to get piped upon generation. This is because output is typically only printed when the pipe's buffer fills up (which is in kilobytes I belive), and when the stdin message ends. This is probably to save on read/writes. You could do this after every print, or if you are looping, after the last print within the loop.



      import sys
      ...
      print('Some message')
      sys.stdout.flush()





      share|improve this answer










      New contributor




      Davey is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.















      • 4





        If you have read this far, please don't be thinking of closing and re-opening the file to do this, the seeks will be a problem, especially for very large files. (I've seen this done!).

        – mckenzm
        21 hours ago






      • 2





        You can also use print's flush parameter to do just as well. For example, print('some message', flush=True).

        – Dan
        12 hours ago







      • 4





        It has nothing to do with the pipe's buffer, but with the stdout mechanism which doesn't flush after newline if it doesn't write to a tty.

        – glglgl
        11 hours ago













      29












      29








      29







      You may also need to explicitly flush the buffer for it to get piped upon generation. This is because output is typically only printed when the pipe's buffer fills up (which is in kilobytes I belive), and when the stdin message ends. This is probably to save on read/writes. You could do this after every print, or if you are looping, after the last print within the loop.



      import sys
      ...
      print('Some message')
      sys.stdout.flush()





      share|improve this answer










      New contributor




      Davey is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      You may also need to explicitly flush the buffer for it to get piped upon generation. This is because output is typically only printed when the pipe's buffer fills up (which is in kilobytes I belive), and when the stdin message ends. This is probably to save on read/writes. You could do this after every print, or if you are looping, after the last print within the loop.



      import sys
      ...
      print('Some message')
      sys.stdout.flush()






      share|improve this answer










      New contributor




      Davey is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this answer



      share|improve this answer








      edited 20 hours ago









      user2313067

      2,1001911




      2,1001911






      New contributor




      Davey is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      answered yesterday









      DaveyDavey

      32625




      32625




      New contributor




      Davey is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Davey is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Davey is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      • 4





        If you have read this far, please don't be thinking of closing and re-opening the file to do this, the seeks will be a problem, especially for very large files. (I've seen this done!).

        – mckenzm
        21 hours ago






      • 2





        You can also use print's flush parameter to do just as well. For example, print('some message', flush=True).

        – Dan
        12 hours ago







      • 4





        It has nothing to do with the pipe's buffer, but with the stdout mechanism which doesn't flush after newline if it doesn't write to a tty.

        – glglgl
        11 hours ago












      • 4





        If you have read this far, please don't be thinking of closing and re-opening the file to do this, the seeks will be a problem, especially for very large files. (I've seen this done!).

        – mckenzm
        21 hours ago






      • 2





        You can also use print's flush parameter to do just as well. For example, print('some message', flush=True).

        – Dan
        12 hours ago







      • 4





        It has nothing to do with the pipe's buffer, but with the stdout mechanism which doesn't flush after newline if it doesn't write to a tty.

        – glglgl
        11 hours ago







      4




      4





      If you have read this far, please don't be thinking of closing and re-opening the file to do this, the seeks will be a problem, especially for very large files. (I've seen this done!).

      – mckenzm
      21 hours ago





      If you have read this far, please don't be thinking of closing and re-opening the file to do this, the seeks will be a problem, especially for very large files. (I've seen this done!).

      – mckenzm
      21 hours ago




      2




      2





      You can also use print's flush parameter to do just as well. For example, print('some message', flush=True).

      – Dan
      12 hours ago






      You can also use print's flush parameter to do just as well. For example, print('some message', flush=True).

      – Dan
      12 hours ago





      4




      4





      It has nothing to do with the pipe's buffer, but with the stdout mechanism which doesn't flush after newline if it doesn't write to a tty.

      – glglgl
      11 hours ago





      It has nothing to do with the pipe's buffer, but with the stdout mechanism which doesn't flush after newline if it doesn't write to a tty.

      – glglgl
      11 hours ago













      18














      Instead of trying to tail a live file, use tee instead. It was made to do exactly what you're trying to do.



      From man tee:




      tee(1) - Linux man page



      Name tee - read from standard input and write to standard output and files



      Synopsis



      tee [OPTION]... [FILE]...


      Description



      Copy standard input to each FILE, and also to standard output.



      -a, --append 
      append to the given FILEs, do not overwrite
      -i, --ignore-interrupts
      ignore interrupt signals
      --help
      display this help and exit
      --version
      output version information and exit


      If a FILE is -, copy again to standard output.




      So in your case you'd run:



      python myprog.py | tee output.txt


      EDIT: As others have pointed out, this answer will run into the same issue OP was originally having unless sys.stdout.flush() is used in the python program as described in Davey's accepted answer. The testing I did before posting this answer did not accurately reflect OP's use-case.



      tee can still be used as an alternative--albeit less than optimal--method of displaying the output while also writing to the file, but Davey's answer is clearly the correct and best answer.






      share|improve this answer

























      • tail in another thread is a good solution for when you've started the application before you decide you want to see the output though.

        – Baldrickk
        17 hours ago






      • 7





        That requires a permanent console session, this is why it’s often much easier to use tail -F or even better the follow function of less. But in all cases the flush should be used.

        – eckes
        15 hours ago






      • 3





        This won't solve the problem that the OP is having. Python's output to the pipe will be buffered just like output to the file.

        – Barmar
        7 hours ago















      18














      Instead of trying to tail a live file, use tee instead. It was made to do exactly what you're trying to do.



      From man tee:




      tee(1) - Linux man page



      Name tee - read from standard input and write to standard output and files



      Synopsis



      tee [OPTION]... [FILE]...


      Description



      Copy standard input to each FILE, and also to standard output.



      -a, --append 
      append to the given FILEs, do not overwrite
      -i, --ignore-interrupts
      ignore interrupt signals
      --help
      display this help and exit
      --version
      output version information and exit


      If a FILE is -, copy again to standard output.




      So in your case you'd run:



      python myprog.py | tee output.txt


      EDIT: As others have pointed out, this answer will run into the same issue OP was originally having unless sys.stdout.flush() is used in the python program as described in Davey's accepted answer. The testing I did before posting this answer did not accurately reflect OP's use-case.



      tee can still be used as an alternative--albeit less than optimal--method of displaying the output while also writing to the file, but Davey's answer is clearly the correct and best answer.






      share|improve this answer

























      • tail in another thread is a good solution for when you've started the application before you decide you want to see the output though.

        – Baldrickk
        17 hours ago






      • 7





        That requires a permanent console session, this is why it’s often much easier to use tail -F or even better the follow function of less. But in all cases the flush should be used.

        – eckes
        15 hours ago






      • 3





        This won't solve the problem that the OP is having. Python's output to the pipe will be buffered just like output to the file.

        – Barmar
        7 hours ago













      18












      18








      18







      Instead of trying to tail a live file, use tee instead. It was made to do exactly what you're trying to do.



      From man tee:




      tee(1) - Linux man page



      Name tee - read from standard input and write to standard output and files



      Synopsis



      tee [OPTION]... [FILE]...


      Description



      Copy standard input to each FILE, and also to standard output.



      -a, --append 
      append to the given FILEs, do not overwrite
      -i, --ignore-interrupts
      ignore interrupt signals
      --help
      display this help and exit
      --version
      output version information and exit


      If a FILE is -, copy again to standard output.




      So in your case you'd run:



      python myprog.py | tee output.txt


      EDIT: As others have pointed out, this answer will run into the same issue OP was originally having unless sys.stdout.flush() is used in the python program as described in Davey's accepted answer. The testing I did before posting this answer did not accurately reflect OP's use-case.



      tee can still be used as an alternative--albeit less than optimal--method of displaying the output while also writing to the file, but Davey's answer is clearly the correct and best answer.






      share|improve this answer















      Instead of trying to tail a live file, use tee instead. It was made to do exactly what you're trying to do.



      From man tee:




      tee(1) - Linux man page



      Name tee - read from standard input and write to standard output and files



      Synopsis



      tee [OPTION]... [FILE]...


      Description



      Copy standard input to each FILE, and also to standard output.



      -a, --append 
      append to the given FILEs, do not overwrite
      -i, --ignore-interrupts
      ignore interrupt signals
      --help
      display this help and exit
      --version
      output version information and exit


      If a FILE is -, copy again to standard output.




      So in your case you'd run:



      python myprog.py | tee output.txt


      EDIT: As others have pointed out, this answer will run into the same issue OP was originally having unless sys.stdout.flush() is used in the python program as described in Davey's accepted answer. The testing I did before posting this answer did not accurately reflect OP's use-case.



      tee can still be used as an alternative--albeit less than optimal--method of displaying the output while also writing to the file, but Davey's answer is clearly the correct and best answer.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 3 hours ago

























      answered yesterday









      n8ten8te

      5,33972235




      5,33972235












      • tail in another thread is a good solution for when you've started the application before you decide you want to see the output though.

        – Baldrickk
        17 hours ago






      • 7





        That requires a permanent console session, this is why it’s often much easier to use tail -F or even better the follow function of less. But in all cases the flush should be used.

        – eckes
        15 hours ago






      • 3





        This won't solve the problem that the OP is having. Python's output to the pipe will be buffered just like output to the file.

        – Barmar
        7 hours ago

















      • tail in another thread is a good solution for when you've started the application before you decide you want to see the output though.

        – Baldrickk
        17 hours ago






      • 7





        That requires a permanent console session, this is why it’s often much easier to use tail -F or even better the follow function of less. But in all cases the flush should be used.

        – eckes
        15 hours ago






      • 3





        This won't solve the problem that the OP is having. Python's output to the pipe will be buffered just like output to the file.

        – Barmar
        7 hours ago
















      tail in another thread is a good solution for when you've started the application before you decide you want to see the output though.

      – Baldrickk
      17 hours ago





      tail in another thread is a good solution for when you've started the application before you decide you want to see the output though.

      – Baldrickk
      17 hours ago




      7




      7





      That requires a permanent console session, this is why it’s often much easier to use tail -F or even better the follow function of less. But in all cases the flush should be used.

      – eckes
      15 hours ago





      That requires a permanent console session, this is why it’s often much easier to use tail -F or even better the follow function of less. But in all cases the flush should be used.

      – eckes
      15 hours ago




      3




      3





      This won't solve the problem that the OP is having. Python's output to the pipe will be buffered just like output to the file.

      – Barmar
      7 hours ago





      This won't solve the problem that the OP is having. Python's output to the pipe will be buffered just like output to the file.

      – Barmar
      7 hours ago











      7














      Run python with the unbuffered flag:



      python -u myprog.py > output.txt


      Output will then print in real time.






      share|improve this answer








      New contributor




      BHC is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.
























        7














        Run python with the unbuffered flag:



        python -u myprog.py > output.txt


        Output will then print in real time.






        share|improve this answer








        New contributor




        BHC is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






















          7












          7








          7







          Run python with the unbuffered flag:



          python -u myprog.py > output.txt


          Output will then print in real time.






          share|improve this answer








          New contributor




          BHC is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.










          Run python with the unbuffered flag:



          python -u myprog.py > output.txt


          Output will then print in real time.







          share|improve this answer








          New contributor




          BHC is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          share|improve this answer



          share|improve this answer






          New contributor




          BHC is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          answered 8 hours ago









          BHCBHC

          711




          711




          New contributor




          BHC is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.





          New contributor





          BHC is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          BHC is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.





















              3














              Terminology: There is no pipe anywhere in this scenario. (I edited the question to fix that). Pipes are a different type of file (a buffer inside the kernel).



              This is a redirect to a regular file.



              C stdio, and Python, default to making stdout line-buffered when it's connected to a TTY, otherwise it's full-buffered. Line-buffered means the buffer is flushed after a newline. Full-buffered means it's only flushed to become visible to the OS (i.e. with a write() system call) when it's full.



              You will see output eventually, in chunks of maybe 4kiB at a time. (I don't know the default buffer size.) This is generally more efficient, and means fewer writes to your actual disk. But not great for interactive monitoring, because output is hidden inside the memory of the writing process until it's flushed.



              On Stack Overflow, there's a Disable output buffering Python Q&A which lists many ways to get unbuffered (or line-buffered?) output to stdout in Python. The question itself summarizes the answers.



              Options include running python -u (Or I guess putting #!/usr/bin/python -u at the top of your script), or using the PYTHONUNBUFFERED environment variable for that program. Or explicit flushing after some/all print functions, like @Davey's answer suggests.




              Some other programs have similar options, e.g. GNU grep has --line-buffered, and GNU sed has -u / --unbuffered, for use-cases like this, or for example piping the output of your python program. e.g. ./slowly-output-stuff | grep --line-buffered 'foo.*bar'.






              share|improve this answer



























                3














                Terminology: There is no pipe anywhere in this scenario. (I edited the question to fix that). Pipes are a different type of file (a buffer inside the kernel).



                This is a redirect to a regular file.



                C stdio, and Python, default to making stdout line-buffered when it's connected to a TTY, otherwise it's full-buffered. Line-buffered means the buffer is flushed after a newline. Full-buffered means it's only flushed to become visible to the OS (i.e. with a write() system call) when it's full.



                You will see output eventually, in chunks of maybe 4kiB at a time. (I don't know the default buffer size.) This is generally more efficient, and means fewer writes to your actual disk. But not great for interactive monitoring, because output is hidden inside the memory of the writing process until it's flushed.



                On Stack Overflow, there's a Disable output buffering Python Q&A which lists many ways to get unbuffered (or line-buffered?) output to stdout in Python. The question itself summarizes the answers.



                Options include running python -u (Or I guess putting #!/usr/bin/python -u at the top of your script), or using the PYTHONUNBUFFERED environment variable for that program. Or explicit flushing after some/all print functions, like @Davey's answer suggests.




                Some other programs have similar options, e.g. GNU grep has --line-buffered, and GNU sed has -u / --unbuffered, for use-cases like this, or for example piping the output of your python program. e.g. ./slowly-output-stuff | grep --line-buffered 'foo.*bar'.






                share|improve this answer

























                  3












                  3








                  3







                  Terminology: There is no pipe anywhere in this scenario. (I edited the question to fix that). Pipes are a different type of file (a buffer inside the kernel).



                  This is a redirect to a regular file.



                  C stdio, and Python, default to making stdout line-buffered when it's connected to a TTY, otherwise it's full-buffered. Line-buffered means the buffer is flushed after a newline. Full-buffered means it's only flushed to become visible to the OS (i.e. with a write() system call) when it's full.



                  You will see output eventually, in chunks of maybe 4kiB at a time. (I don't know the default buffer size.) This is generally more efficient, and means fewer writes to your actual disk. But not great for interactive monitoring, because output is hidden inside the memory of the writing process until it's flushed.



                  On Stack Overflow, there's a Disable output buffering Python Q&A which lists many ways to get unbuffered (or line-buffered?) output to stdout in Python. The question itself summarizes the answers.



                  Options include running python -u (Or I guess putting #!/usr/bin/python -u at the top of your script), or using the PYTHONUNBUFFERED environment variable for that program. Or explicit flushing after some/all print functions, like @Davey's answer suggests.




                  Some other programs have similar options, e.g. GNU grep has --line-buffered, and GNU sed has -u / --unbuffered, for use-cases like this, or for example piping the output of your python program. e.g. ./slowly-output-stuff | grep --line-buffered 'foo.*bar'.






                  share|improve this answer













                  Terminology: There is no pipe anywhere in this scenario. (I edited the question to fix that). Pipes are a different type of file (a buffer inside the kernel).



                  This is a redirect to a regular file.



                  C stdio, and Python, default to making stdout line-buffered when it's connected to a TTY, otherwise it's full-buffered. Line-buffered means the buffer is flushed after a newline. Full-buffered means it's only flushed to become visible to the OS (i.e. with a write() system call) when it's full.



                  You will see output eventually, in chunks of maybe 4kiB at a time. (I don't know the default buffer size.) This is generally more efficient, and means fewer writes to your actual disk. But not great for interactive monitoring, because output is hidden inside the memory of the writing process until it's flushed.



                  On Stack Overflow, there's a Disable output buffering Python Q&A which lists many ways to get unbuffered (or line-buffered?) output to stdout in Python. The question itself summarizes the answers.



                  Options include running python -u (Or I guess putting #!/usr/bin/python -u at the top of your script), or using the PYTHONUNBUFFERED environment variable for that program. Or explicit flushing after some/all print functions, like @Davey's answer suggests.




                  Some other programs have similar options, e.g. GNU grep has --line-buffered, and GNU sed has -u / --unbuffered, for use-cases like this, or for example piping the output of your python program. e.g. ./slowly-output-stuff | grep --line-buffered 'foo.*bar'.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 5 hours ago









                  Peter CordesPeter Cordes

                  2,4751621




                  2,4751621





















                      0














                      Another option (if you don't care about the contents, just the progress) is pv:



                      NAME
                      pv - monitor the progress of data through a pipe

                      SYNOPSIS
                      pv [OPTION] [FILE]...
                      pv [-h|-V]


                      Introduce this in your pipeline and it will show you the number of bytes processed as well as the speed they go through the pipeline.



                      If the content is what you actually want to monitor, then tee is the best choice, as the other answer indicates.






                      share|improve this answer


















                      • 1





                        There's no pipeline, just file redirection. And it won't solve the buffering problem.

                        – Barmar
                        6 hours ago















                      0














                      Another option (if you don't care about the contents, just the progress) is pv:



                      NAME
                      pv - monitor the progress of data through a pipe

                      SYNOPSIS
                      pv [OPTION] [FILE]...
                      pv [-h|-V]


                      Introduce this in your pipeline and it will show you the number of bytes processed as well as the speed they go through the pipeline.



                      If the content is what you actually want to monitor, then tee is the best choice, as the other answer indicates.






                      share|improve this answer


















                      • 1





                        There's no pipeline, just file redirection. And it won't solve the buffering problem.

                        – Barmar
                        6 hours ago













                      0












                      0








                      0







                      Another option (if you don't care about the contents, just the progress) is pv:



                      NAME
                      pv - monitor the progress of data through a pipe

                      SYNOPSIS
                      pv [OPTION] [FILE]...
                      pv [-h|-V]


                      Introduce this in your pipeline and it will show you the number of bytes processed as well as the speed they go through the pipeline.



                      If the content is what you actually want to monitor, then tee is the best choice, as the other answer indicates.






                      share|improve this answer













                      Another option (if you don't care about the contents, just the progress) is pv:



                      NAME
                      pv - monitor the progress of data through a pipe

                      SYNOPSIS
                      pv [OPTION] [FILE]...
                      pv [-h|-V]


                      Introduce this in your pipeline and it will show you the number of bytes processed as well as the speed they go through the pipeline.



                      If the content is what you actually want to monitor, then tee is the best choice, as the other answer indicates.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 9 hours ago









                      rrauenzarrauenza

                      1313




                      1313







                      • 1





                        There's no pipeline, just file redirection. And it won't solve the buffering problem.

                        – Barmar
                        6 hours ago












                      • 1





                        There's no pipeline, just file redirection. And it won't solve the buffering problem.

                        – Barmar
                        6 hours ago







                      1




                      1





                      There's no pipeline, just file redirection. And it won't solve the buffering problem.

                      – Barmar
                      6 hours ago





                      There's no pipeline, just file redirection. And it won't solve the buffering problem.

                      – Barmar
                      6 hours ago

















                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Super User!


                      • 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%2fsuperuser.com%2fquestions%2f1421123%2fwatching-something-be-written-to-a-file-live-with-tail%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

                      Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                      Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                      Tom Holland Mục lục Đầu đời và giáo dục | Sự nghiệp | Cuộc sống cá nhân | Phim tham gia | Giải thưởng và đề cử | Chú thích | Liên kết ngoài | Trình đơn chuyển hướngProfile“Person Details for Thomas Stanley Holland, "England and Wales Birth Registration Index, 1837-2008" — FamilySearch.org”"Meet Tom Holland... the 16-year-old star of The Impossible""Schoolboy actor Tom Holland finds himself in Oscar contention for role in tsunami drama"“Naomi Watts on the Prince William and Harry's reaction to her film about the late Princess Diana”lưu trữ"Holland and Pflueger Are West End's Two New 'Billy Elliots'""I'm so envious of my son, the movie star! British writer Dominic Holland's spent 20 years trying to crack Hollywood - but he's been beaten to it by a very unlikely rival"“Richard and Margaret Povey of Jersey, Channel Islands, UK: Information about Thomas Stanley Holland”"Tom Holland to play Billy Elliot""New Billy Elliot leaving the garage"Billy Elliot the Musical - Tom Holland - Billy"A Tale of four Billys: Tom Holland""The Feel Good Factor""Thames Christian College schoolboys join Myleene Klass for The Feelgood Factor""Government launches £600,000 arts bursaries pilot""BILLY's Chapman, Holland, Gardner & Jackson-Keen Visit Prime Minister""Elton John 'blown away' by Billy Elliot fifth birthday" (video with John's interview and fragments of Holland's performance)"First News interviews Arrietty's Tom Holland"“33rd Critics' Circle Film Awards winners”“National Board of Review Current Awards”Bản gốc"Ron Howard Whaling Tale 'In The Heart Of The Sea' Casts Tom Holland"“'Spider-Man' Finds Tom Holland to Star as New Web-Slinger”lưu trữ“Captain America: Civil War (2016)”“Film Review: ‘Captain America: Civil War’”lưu trữ“‘Captain America: Civil War’ review: Choose your own avenger”lưu trữ“The Lost City of Z reviews”“Sony Pictures and Marvel Studios Find Their 'Spider-Man' Star and Director”“‘Mary Magdalene’, ‘Current War’ & ‘Wind River’ Get 2017 Release Dates From Weinstein”“Lionsgate Unleashing Daisy Ridley & Tom Holland Starrer ‘Chaos Walking’ In Cannes”“PTA's 'Master' Leads Chicago Film Critics Nominations, UPDATED: Houston and Indiana Critics Nominations”“Nominaciones Goya 2013 Telecinco Cinema – ENG”“Jameson Empire Film Awards: Martin Freeman wins best actor for performance in The Hobbit”“34th Annual Young Artist Awards”Bản gốc“Teen Choice Awards 2016—Captain America: Civil War Leads Second Wave of Nominations”“BAFTA Film Award Nominations: ‘La La Land’ Leads Race”“Saturn Awards Nominations 2017: 'Rogue One,' 'Walking Dead' Lead”Tom HollandTom HollandTom HollandTom Hollandmedia.gettyimages.comWorldCat Identities300279794no20130442900000 0004 0355 42791085670554170004732cb16706349t(data)XX5557367