From eb3396bed9d0032139bb8472c7ede4ec6c9c2aea Mon Sep 17 00:00:00 2001 From: memsharded Date: Mon, 19 Feb 2024 17:00:48 +0100 Subject: [PATCH] print to stderr --- conans/client/loader.py | 8 ++++- .../conanfile/test_print_in_conanfile.py | 35 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 conans/test/integration/conanfile/test_print_in_conanfile.py diff --git a/conans/client/loader.py b/conans/client/loader.py index 66086f71197..88e24892c1e 100644 --- a/conans/client/loader.py +++ b/conans/client/loader.py @@ -205,7 +205,8 @@ def load_conanfile_txt(self, conan_txt_path): conanfile._conan_is_consumer = True return conanfile - def _parse_conan_txt(self, contents, path, display_name): + @staticmethod + def _parse_conan_txt(contents, path, display_name): conanfile = ConanFile(display_name) try: @@ -320,6 +321,9 @@ def _load_python_file(conan_file_path): if not os.path.exists(conan_file_path): raise NotFoundException("%s not found!" % conan_file_path) + def new_print(*args, **kwargs): # Make sure that all user python files print() goes to stderr + print(*args, **kwargs, file=sys.stderr) + module_id = str(uuid.uuid1()) current_dir = os.path.dirname(conan_file_path) sys.path.insert(0, current_dir) @@ -362,6 +366,7 @@ def _load_python_file(conan_file_path): else: if folder.startswith(current_dir): module = sys.modules.pop(added) + module.print = new_print sys.modules["%s.%s" % (module_id, added)] = module except ConanException: raise @@ -373,6 +378,7 @@ def _load_python_file(conan_file_path): finally: sys.path.pop(0) + loaded.print = new_print return loaded, module_id diff --git a/conans/test/integration/conanfile/test_print_in_conanfile.py b/conans/test/integration/conanfile/test_print_in_conanfile.py new file mode 100644 index 00000000000..64705e8e8c2 --- /dev/null +++ b/conans/test/integration/conanfile/test_print_in_conanfile.py @@ -0,0 +1,35 @@ +import json +import textwrap + +from conans.test.utils.tools import TestClient + + +def test_print_in_conanfile(): + """ + Tests that prints in conanfiles will not ruin json stdout outputs + """ + c = TestClient(light=True) + other = textwrap.dedent(""" + def myprint(text): + print(text) + """) + conanfile = textwrap.dedent(""" + import other + from conan import ConanFile + + class MyTest(ConanFile): + name = "pkg" + version = "0.1" + + def generate(self): + print("Hello world!!") + other.myprint("Bye world!!") + """) + c.save({"other.py": other, + "conanfile.py": conanfile}) + c.run("install . --format=json") + assert "Hello world!!" in c.stderr + assert "Bye world!!" in c.stderr + info = json.loads(c.stdout) + # the json is correctly loaded + assert "graph" in info