0

I want to connect two PCs, but when one of the PCs is not on I get an exception that the connection was refused, because the other PC isn't on, so I thought that when this exception happens I just re-execute this part until it succeeds, so when the other PC turns on.

This is what I have:

def main():
    s = socket.socket()
    host = "Alex-PC"
    port = 8080
    s.connect((host,port))

    if traceback.format_exception(ConnectionRefusedError):
        main()

I thought that an if statement might work, but I have no idea how to write the if statement for this problem.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • Did you read the [tutorial](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) already? – mkrieger1 Dec 22 '21 at 15:59
  • Your mistake was to focus on the word "traceback". A traceback is the information that is attached to an exception that is telling you where the error happened. What you were looking for is "exception handling". – mkrieger1 Dec 22 '21 at 16:00
  • You also might need to be careful here as calling `main()` recursively will reach a default threshold surprisingly quickly. – JonSG Dec 22 '21 at 16:04
  • You should also read [this earlier part of the tutorial](https://docs.python.org/3/tutorial/introduction.html#first-steps-towards-programming) which teaches you how to repeat stuff. – mkrieger1 Dec 22 '21 at 16:05
  • 1
    See also https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response for more complete examples. – mkrieger1 Dec 22 '21 at 16:06

2 Answers2

0

you can use this method when calling you function:

temp = 1

def main():
    s = socket.socket()
    host = "Alex-PC"
    port = 8080
    s.connect((host,port))
    temp = 0

while(1):
    if temp == 1:
        try:
            main()
        except:
            temp = 1
    elif temp == 0: break
  • 1
    @JonSG Actually, it creates an infinite loop, because `temp` is global, so it never gets set to zero, and the while-loop never breaks. – ekhumoro Dec 22 '21 at 16:35
  • @ekhumoro Oh ya, right.. It is more convoluted than I though :-) – JonSG Dec 22 '21 at 16:47
0

When you want to handle an exception (such ConnectionRefusedError), you should use a Try/Except clause.

This will try to execute the code inside the try and, if it fails, it will execute the except clause (if the raised Exception matches with the declared on the except)

EDIT with the suggestions from comments:

In your specific case, you can do something like the following:


import threading
import socket
t = 1

def connect(s, host, port):
    try:
        s.connect((host,port))
    except:
        print(f"Host {host} is not available. Retrying in {t} seconds...")
        time.sleep(t)
        t*=2
        connect(s, host, port)
        
def main():
    s = socket.socket()
    host = "Alex-PC"
    port = 8080
    connect(s, host, port)
Latra
  • 492
  • 3
  • 14
  • 1
    Note that you probably don't want to recursively call `connect()` like this as python has a default depth of only 1000. So if one is waiting for a second PC to be powered on, this will reach the recursion depth in the blink of an eye. – JonSG Dec 22 '21 at 16:16
  • This will raise a `NameError`, since `port` is undefined. Also, the except-block will raise a `TypeError`, since `connect` is called without the required arguments. – ekhumoro Dec 22 '21 at 16:23
  • You are right. Edited. I just wanted to show them the try/except clause and I didn't put care on details – Latra Dec 22 '21 at 16:30
  • @Latra You still haven't fixed all the errors. Both the `connect` calls have missing arguments, and `time.sleep` will rasie an `NameError`. But calling `connect` recursively like that is still a *very bad idea*. Just use a for-loop in `main`. – ekhumoro Dec 22 '21 at 16:48