I have a py script S1 that I would need to execute inside a screen. On an end-user point of view, I would like them to just execute another python script S2, which will open a screen and execute the script S1 inside that screen.

My S2.py is like this :

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

What I want is that end-users can simply run python S2.py, the screen hassle is handled by me at the back. I will need to have extra mechanism to clean up screen, use existing screens etc. Giving users instruction to open screen themselves will litter every terminal with screens.

The reason S1.py needs to be inside screen is due to SSH connection stability if run on main Terminal.


1 Answer 1


Probably best to use subprocess and write the command to screen's stdin.

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

You'll probably want to brush up on subprocess.Popen's documentation because there are probably specifics about how to close subprocesses like that properly, but this should get you on the right track.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .