1

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.

  • 1
    `subprocess` should have worked - did you capture both STDOUT and STDERR? I'm not sure which channel those messages are sent to. – jasonharper Jul 13 '20 at 19:06
  • I still cannot get `subprocess` to work: ```import subprocess from time import sleep afil = open('r.txt', 'wb') bfil = open('t.txt', 'wb') sub = subprocess.Popen('cmd /k python', shell=True, stdout=afil, stderr=bfil) sleep(5) sub.terminate() sub.kill() afil.close() bfil.close()``` gives me `\nC:/Users/Brainfart>` in `r.txt` and `\n` in `b.txt`. Any help is appreciated. – Mr. Brainfart Jul 13 '20 at 20:52

1 Answers1

1

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 '>>>'
  • Changed the subprocess call from using `python` to using `sys.executable`. This approach is better because it ensures that you get the header from the same python as your script is run in. – Mr. Brainfart Jul 14 '20 at 11:20