CloudCompare / CloudComPy

Python wrapper for CloudCompare
Other
283 stars 40 forks source link

Messages on import: QFileSystemWatcher and JsonRPCPlugin (Windows 10) #101

Closed bthetford closed 1 year ago

bthetford commented 1 year ago

import cloudComPy as cc is generating the following console messages for me:

QFileSystemWatcher: Removable drive notification will not work if there is no QCoreApplication instance.
JsonRPCPlugin::JsonRPCPlugin

This occurs weather I'm using python interactively (python -i) or importing the module within a script. I tried using this trick to suppress output temporarily, but no luck.

Not a huge deal but I'm trying to have a clean console for my own output! Thanks, Beau

prascle commented 1 year ago

Hi, following your link, I found this one that works for CloudComPy import, redirecting stderr instead of stdout.

Regards, Paul

import os
import sys
from contextlib import contextmanager

@contextmanager
def stderr_redirected(to=os.devnull):
    '''
    # from https://stackoverflow.com/questions/5081657/how-do-i-prevent-a-c-shared-library-to-print-on-stdout-in-python/17954769#17954769
    import os

    with stderr_redirected(to=filename):
        print("from Python")
        os.system("echo non-Python applications are also supported")
    '''
    fd = sys.stderr.fileno()

    ##### assert that Python and C stdio write using the same file descriptor
    ####assert libc.fileno(ctypes.c_void_p.in_dll(libc, "stderr")) == fd == 1

    def _redirect_stderr(to):
        sys.stderr.close() # + implicit flush()
        os.dup2(to.fileno(), fd) # fd writes to 'to' file
        sys.stderr = os.fdopen(fd, 'w') # Python writes to fd

    with os.fdopen(os.dup(fd), 'w') as old_stderr:
        with open(to, 'w') as file:
            _redirect_stderr(to=file)
        try:
            yield # allow code to be run with the redirected stderr
        finally:
            _redirect_stderr(to=old_stderr) # restore stderr.
                                            # buffering and flags such as
                                            # CLOEXEC may be different

with stderr_redirected():
    import cloudComPy as cc
bthetford commented 1 year ago

Awesome, that works perfectly, thanks! Beau