Ev.*_*nis 5 python import sys python-3.x
我正在查看print哪些状态的Python文档:
print(*objects,sep ='',end ='\n',file = sys.stdout,flush = False)
可以看出,如果file未指定要打印的内容,sys.stdout则使用默认值,这让我思考.
调用print肯定不会 sys在后台导入,那么它是如何工作的?
是sys.stdout莫名其妙地到达其他地方?
例:
我正在使用PyCharm,我想创建一个函数,可以将消息打印text到文件或标准输出.我开始写作:
def my_print(text, file=None):
print(text, file=file if file is not None else ?)
Run Code Online (Sandbox Code Playgroud)
那么接下来else呢?sys.stdout不起作用,显然,我对冗长不感兴趣:
def my_print(text, file=None):
if file is None:
print(text)
else:
print(text, file=file)
Run Code Online (Sandbox Code Playgroud)
另一个答案指出 print 是用 C 实现的。但是,即使它是用 Python 实现的,也不意味着它sys可以在任何地方使用。
考虑这段代码:
实用程序.py
import sys
def my_print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False):
file.write(sep.join(objects))
Run Code Online (Sandbox Code Playgroud)
主要.py
from utils import print
my_print('foo')
Run Code Online (Sandbox Code Playgroud)
这里sys仅在 utils 中可用,但 print 仍会输出到,sys.stdout而无法从 main 访问它。
| 归档时间: |
|
| 查看次数: |
50 次 |
| 最近记录: |