0

I want to call 2 python scripts using tcp Conditionally via another main script. So, when my data sent to the main script is "YES", the first script executed and when data = "No", the second script executed! the problem is that when the data sent "YES" the first script runs, but when the data sent "No", the second one does not execute, so I realized that I have to add a condition to kill the first one in order to run the second and vice versa, so how can I do it? Help me, please!

#main script
#!/usr/bin/env python
import os
import socket
backlog = 1
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('192.168.43.95', 12345))
s.listen(backlog)
try:
    print ("is waiting")
    client, address = s.accept()
    while True:
        data = client.recv(size)
        if data == "YES \n":
            os.system('python script1.py')
        elif data == "No \n":
            os.system('python script2.py')
except:
    print("closing socket")
    client.close()
    s.close()
ninpi
  • 17
  • 7

2 Answers2

0

Whether you need to kill the script all depends on how you want the program to behave. os.system() is blocking. That means that the main script is NOT executing (is blocked) while whatever you called with os.system() is running - in your case that's either python script1.py or python script2.py. So if you send "YES" and after that "No", would get started and script2 will get executed only after script1 has finished.

If you want the execution of script1 and script2 happen concurrently, you should use Popen from the subprocess library.

If you want to kill the script that started running first when you got a new command (generally not a good idea, but there are uses for it), you can use Popen.kill().

Faboor
  • 1,365
  • 2
  • 10
  • 23
  • I just want them to run in an alternative way when the first runs the second ends and vice versa and all in a loop! – ninpi Jun 15 '19 at 23:35
  • I saw the solution you offered me in another location https://stackoverflow.com/questions/36676205/how-to-stop-another-already-running-script-in-python?noredirect=1&lq=1 but it seems a bit complicated, is there a simpler solution? – ninpi Jun 16 '19 at 00:10
  • @ninpi if you want them to just alternate, why even bother with recognising whether it's a "YES" or "No"? – Faboor Jun 16 '19 at 16:20
  • I want to control using a toggle (button) these two scripts if the button in position 1 script 1 runs otherwise script 2 runs! – ninpi Jun 16 '19 at 21:45
0

just add

tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

to use same address again

islamgab
  • 1
  • 2
  • but I used the tcp login script only in the main script! – ninpi Jun 15 '19 at 23:59
  • what about if i have to use in both scripts 1 &2 login tcp and in the main script too (in 3 scripts), i added this line to script 1 &2 it shows me an error that i used the same adress! can you help me please! – ninpi Jun 17 '19 at 00:19