如何获得完整的解释器启动横幅

2024-06-06 15:43:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用Python获取启动横幅信息,而不仅仅是:

f'''Python {sys.version} on {sys.platform}
Type "help", "copyright", "credits", or "license" for more information.'''

其结果是:

Python 3.8.3 (default, Jul 2 2020, 17:30:36) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

但完整的启动横幅包括所有错误和分发,例如:

Python 3.8.3 (default, Jul  2 2020, 17:30:36) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32

Warning:
This Python interpreter is in a conda environment, but the environment has
not been activated. Libraries may fail to load. To activate this environment
please see https://conda.io/activation.

Type "help", "copyright", "credits" or "license" for more information.

我想在subprocess.Popen中运行python,然后终止它,但我无法捕获启动横幅输出


Tags: ordefaultforinformationenvironmentlicenseonmore
1条回答
网友
1楼 · 发布于 2024-06-06 15:43:06

我终于想出了这个问题。结果证明subprocess.Popen是正确的答案。有趣的是,头被打印到stderr而不是stdout。 对我有用的代码:

from subprocess import (Popen, PIPE)
from os import devnull
from sys import executable
from time import sleep
nump = open(devnull, 'w+') #Making a dud file so the stdin won't be the same as the main interpreter
hed = Popen(executable, shell=True, stdout=PIPE, stderr=PIPE, stdin=nump)
sleep(0.1) #Sleeping so python has time to print the header before we kill it
hed.terminate()
nump.close()
print(hed.stderr.read().decode('utf-8').strip().strip('>>>').strip()) #Removing whitespace and the '>>>'

相关问题 更多 >