Pythonは画面を開き、画面内で実行します。

Pythonは画面を開き、画面内で実行します。

画面内で実行する必要があるpyスクリプトS1があります。エンドユーザーの観点からは、画面を開き、その画面内でスクリプトS1を実行する別のPythonスクリプトS2を実行したいと思います。

私のS2.pyことです。

import os 
os.cmd('echo Outside main terminal')
os.cmd('screen -S sTest')
os.cmd('echo I would like to be inside screen here. Not successfully!. How to send command to screen instead of remaining at main Terminal')
os.cmd('spark-submit S1.py') #this should execute inside screen. currently main Terminal is the one that runs it
#Additional steps to check status, clean up, check if screen is active then spawn another sTest2 sTest3, otherwise close and/or reuse screen sTest, etc.
screen_list = os.cmd('screen -ls')
if 'sTest' in screen_list ...... #let python process

私が望むのは、エンドユーザーが単に実行し、python S2.py画面の面倒は後ろから私が処理することです。画面を消去したり、既存の画面を使用するなどの追加のメカニズムが必要です。ユーザーに画面を直接オンにするように指示することは、すべての端末の画面でいっぱいになります。

画面内になければならない理由は、S1.pyメイン端末での実行時のSSH接続の安定性によるものです。

ベストアンサー1

サブプロセスを使用し、画面の標準入力にコマンドを作成するのが最善です。

proc = subprocess.Popen('screen -S sTest', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
proc.stdin.write('echo I would like to be inside screen here.\n')
proc.stdin.write('spark-submit S1.py\n')
statusProc = subprocess.run('screen -ls', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
statusString = statusProc.stdout.decode('ascii')
# parse screen's output (statusString) for your status list

サブプロセスを適切に閉じる方法に関する具体的な情報がある可能性があるため、subprocess.Popenに関するドキュメントをよく見てください。

おすすめ記事