Search code examples
python-3.xloggingftputil

Python ftputil outputting to terminal although I want to redirect output to a file


I'm running a Python3 script on the terminal, and on my terminal it writes out a lot of print() statements that I added, as well as output from libraries I'm using.

I wish to save the output in a file, so I run the script like this.

python3 myscript.py > logfile.txt

Everything I print() from within Python now goes into the file as I want, instead of being printed to my terminal.

However, within this script I'm also using the ftputil library to download files, and some output from ftputil still shows on the terminal where I ran the script. So now the output of my program is split in 2 parts, which makes it less useful.

download-ftp.py:160: DeprecationWarning: `use_list_a_option` will default to `False` in ftputil 4.x.x with ftputil.FTPHost(ftp_addr, ftp_user, ftp_pw) as ftp_host:

What is needed to make the output from ftputil also go into the file that I want?


Solution

  • You're right, this deprecation warning is from ftputil.

    ftputil uses the Python warnings module to show this warning. The warnings module not only outputs warnings (by default to stderr), but also offers ways to control which warnings are actually shown (see The Warnings Filter and Temporarily Suppressing Warnings).

    You can suppress the ftputil warning with

    import warnings
    
    import ftputil
    
    
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", category=DeprecationWarning)
        ftp_host = ftputil.FTPHost(host, user, password)
    ...
    

    If you really want the deprecation warning in your log file, you can use the methods that others have suggested in the comments. Here's an example:

    import sys
    
    import ftputil           
    
    
    old_stderr = sys.stderr
    sys.stderr = sys.stdout
    try:
        ftp_host = ftputil.FTPHost(host, user, password)
    finally:
        sys.stderr = old_stderr