Mr. Brainfart
Mr. Brainfart

Reputation: 79

How to get full interpreter startup banner

I am trying to get the startup banner info in Python, not just:

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

which results in:

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.

but the full startup banner including any errors and the distribution for example:

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.

I was thinking of running python in subprocess.Popen and then terminate it, but I have not been able to capture the startup banner output.

Upvotes: 1

Views: 193

Answers (1)

Mr. Brainfart
Mr. Brainfart

Reputation: 79

I was finally able to figure this question out. Turns out subprocess.Popen was the right answer. Interestingly the header was printed to stderr instead of stdout. Code that worked for me:

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 '>>>'

Upvotes: 1

Related Questions