绕过Python中的交互模式检测

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年8月5日 06:50:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839479.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定