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()

2 Answers 2

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().

Sign up to request clarification or add additional context in comments.

4 Comments

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!
I saw the solution you offered me in another location stackoverflow.com/questions/36676205/… but it seems a bit complicated, is there a simpler solution?
@ninpi if you want them to just alternate, why even bother with recognising whether it's a "YES" or "No"?
I want to control using a toggle (button) these two scripts if the button in position 1 script 1 runs otherwise script 2 runs!
0

just add

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

to use same address again

2 Comments

but I used the tcp login script only in the main script!
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.