英文:
bypassing interactive mode detection in python
问题
我正在导入一个第三方包,这导致一些语句被打印到控制台、Jupyter笔记本等上,因为在该包的__init__.py
中有这样一个调用:
if hasattr(sys, 'ps1'):
print('hello world')
有没有办法我可以从我的端口绕过这个问题?
英文:
I am importing a third party package and that causes some statements to get printed on the console, jupyter notebook etc because inside the __init__.py
of that package there is a call like:
if hasattr(sys,'ps1'):
print('hello world')
Is there any way I could circumvent this from my end?
答案1
得分: 1
如评论中所指出,删除 sys.ps1
是一种选项。
del sys.ps1
如果你想采用稍微不太永久的(尽管仍然有一定风险的)解决方案,你可以(滥用)Python的测试框架来临时移除该变量。
import sys
from unittest import mock
with mock.patch.dict('sys.__dict__'):
del sys.ps1
import whatever_library
# 在 'with' 块之外,sys.ps1 会恢复其原始值。
这里没有显示:你应该添加一段极其详尽的注释,解释为什么这种不寻常的代码模式是必要的,它实现了什么,以及其中的风险是什么。
英文:
As indicated in the comments, deleting sys.ps1
is an option.
del sys.ps1
If you want to go for a slightly less permanent (though still somewhat risky) solution, you can (ab)use Python's testing framework to temporarily remove the variable.
import sys
from unittest import mock
with mock.patch.dict('sys.__dict__'):
del sys.ps1
import whatever_library
# Outside of the 'with' block, sys.ps1 has its original value.
Not shown here: You should add an extremely lengthy comment explaining why this unusual code pattern is necessary, what it accomplishes, and what the risks are.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论