twasbrillig
twasbrillig

Reputation: 18921

How to tell if you're running through Pythonwin or console

I'm using PythonWin. If in the IDE I click Run, then any input() commands will pop up as a windows message box. But in the console they are printed console commands.

I tried using msvcrt.getch() in PythonWin, and it returns the character \xFF every time.

I would like to have my program use msvcrt.getch() if it's in the console, and input() if it's in PythonWin. So, how can my program tell which one it's running in?

Upvotes: 1

Views: 236

Answers (2)

tmr232
tmr232

Reputation: 1201

You can check if you are in a regular shell (python.exe) or a custom one (IPython, PythonWin, DreamPie...) by using os.isatty:

import os
import sys
import io

try:
    if os.isatty(sys.stdin.fileno()):
        print "msvcrt.getch() will work."
    else:
        print "msvcrt.getch() will fail."
except (AttributeError, io.UnsupportedOperation):
    print "msvcrt.getch() will fail."

Upvotes: 1

twasbrillig
twasbrillig

Reputation: 18921

I was able to figure out a solution by stepping into the source code of input() when running through PythonWin. I am posting here so that others who run across this issue will have a solution.

"pywin.framework.startup" in sys.modules is True when running in PythonWin, but False when running in the console.

So my code looks like this:

if "pywin.framework.startup" in sys.modules:
    move = raw_input(promptstr)
else:
    print(promptstr)
    move = msvcrt.getch()

Upvotes: 1

Related Questions