Python プログラムがターミナルで開始されたのか、それとも Sun Grid Engine のようなバッチ エンジンで開始されたのかを調べる方法はありますか?
アイデアは、いくつかのプログレスバーやその他のASCIIインタラクティブなものを印刷するかどうかを決定することです。
ありがとう!
p。
標準的な方法はisatty()
.
import sys
if sys.stdout.isatty():
print("Interactive")
else:
print("Non-interactive")
を使用os.getppid()
して、このプロセスの親プロセスのプロセス ID を見つけ、そのプロセス ID を使用して、そのプロセスが実行しているプログラムを特定できます。もっと便利に、sys.stdout.isatty()
-- これはタイトルの質問には答えませんが、説明する実際の問題をより適切に解決するように見えます(シェルで実行しているが、出力が他のプロセスにパイプされているか、ファイルにリダイレクトされている場合)おそらく、「インタラクティブなもの」も発行したくないでしょう)。
少し短い:
import sys
sys.stdout.isatty()
LinuxとWindowsの両方で、通常のPythonインタープリターとIPythonの両方で機能することがわかりました(IronPythonについては言えませんが)。
isInteractive = hasattr(sys, 'ps1') or hasattr(sys, 'ipcompleter')
ただし、ipythonを使用する場合、ファイルがコマンドライン引数として指定されていると、インタープリターが対話型になる前に実行されることに注意してください。以下の意味を参照してください。
C:\>cat C:\demo.py
import sys, os
# ps1=python shell; ipcompleter=ipython shell
isInteractive = hasattr(sys, 'ps1') or hasattr(sys, 'ipcompleter')
print isInteractive and "This is interactive" or "Automated"
C:\>python c:\demo.py
Automated
C:\>python
>>> execfile('C:/demo.py')
This is interactive
C:\>ipython C:\demo.py
Automated # NOTE! Then ipython continues to start up...
IPython 0.9.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [2]: run C:/demo.py
This is interactive # NOTE!
HTH