| 3668 | |
| 3669 | PYBIND11_NAMESPACE_BEGIN(detail) |
| 3670 | PYBIND11_NOINLINE void print(const tuple &args, const dict &kwargs) { |
| 3671 | auto strings = tuple(args.size()); |
| 3672 | for (size_t i = 0; i < args.size(); ++i) { |
| 3673 | strings[i] = str(args[i]); |
| 3674 | } |
| 3675 | auto sep = kwargs.contains("sep") ? kwargs["sep"] : str(" "); |
| 3676 | auto line = sep.attr("join")(std::move(strings)); |
| 3677 | |
| 3678 | object file; |
| 3679 | if (kwargs.contains("file")) { |
| 3680 | file = kwargs["file"].cast<object>(); |
| 3681 | } else { |
| 3682 | try { |
| 3683 | file = module_::import("sys").attr("stdout"); |
| 3684 | } catch (const error_already_set &) { |
| 3685 | /* If print() is called from code that is executed as |
| 3686 | part of garbage collection during interpreter shutdown, |
| 3687 | importing 'sys' can fail. Give up rather than crashing the |
| 3688 | interpreter in this case. */ |
| 3689 | return; |
| 3690 | } |
| 3691 | } |
| 3692 | |
| 3693 | auto write = file.attr("write"); |
| 3694 | write(std::move(line)); |
| 3695 | write(kwargs.contains("end") ? kwargs["end"] : str("\n")); |
| 3696 | |
| 3697 | if (kwargs.contains("flush") && kwargs["flush"].cast<bool>()) { |
| 3698 | file.attr("flush")(); |
| 3699 | } |
| 3700 | } |
| 3701 | PYBIND11_NAMESPACE_END(detail) |
| 3702 | |
| 3703 | template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args> |