Reputation: 23
How can I execute different shell scripts (tes1.sh, test2.sh, ..) based on different keyboard events using python.
If user press "1"
execute test1.sh
if "2"
test2.sh
and etc.
I got pressed key using "raw-input" and based on the input value I have called "test1.sh" or "test2.sh" using subprocess.call.
How can I stop running current shell script and run new one if different key is pressed.
Upvotes: 2
Views: 1158
Reputation: 898
Using subprocess.call (according to my knowledge of python docs) is not good idea here because you want to kill (stop) that process after key press... It's better to use subprocess.Popen here, because it doesn't blocks interaction with process while it's running. Subprocess.call waits for program to complete and then returns a code representing the process exit status. To call and kill process, you can do something like this:
import os
import signal
import subprocess
process = subprocess.Popen('script.sh', stdout=subprocess.PIPE,
shell=False, preexec_fn=os.setsid)
os.killpg(process.pid, signal.SIGTERM)
I hope this helps you, if you don't understand something, feel free to ask in comments...
P.S. If you don't know how to check for key press take a look at this part of docs:
https://docs.python.org/2/faq/library.html#how-do-i-get-a-single-keypress-at-a-time
Upvotes: 0
Reputation: 107297
You can use subprocess.call
and raw_input()
for python2 and input
in python3:
import subprocess
num=raw_input('print the number : ')
if num=='1' :
subprocess.call('test1.sh')
elif num == '2':
subprocess.call('test2.sh')
Upvotes: 1