-3

I'm trying to tell whether or not I have network access in python. I'm using:

    interfaces = os.listdir("/sys/class/net")
    for interface in interfaces:
        cards = open("/sys/class/net/" + interface + "/operstate", "r");
        if cards.read() == "up":
            print("network is up")
        cards.close()

Which is never true even though adding a 'print(cards.read())' returns up. I've tried adding a newline character to that if statement as well which doesn't help.

If you know of a better way to tell if I have network access that would also be appreciated.

pvg
  • 2,673
  • 4
  • 17
  • 31
Cnorwood7641
  • 336
  • 1
  • 5
  • 17
  • 5
    What if you use `cards.read().strip()` instead? – Willem Van Onsem May 23 '17 at 14:29
  • If you are trying `print(cards.read())` as a test before you use the value, it would presumably consume the line and the _next_ `cards.read()` would not be `up`. – kojiro May 23 '17 at 14:31
  • @StevenRumbalski OP may not mean it that way. It could be a matter of English usage, such as "my Python if statement is broken, please help". – kojiro May 23 '17 at 14:32
  • 1
    What does `print(repr(cards.read()))` show? – Steven Rumbalski May 23 '17 at 14:34
  • The answer to [Determine Active NIC address using python console commands](https://stackoverflow.com/questions/37716294/determine-active-nic-address-using-python-console-commands) is using `.read().rstrip()` in the accepted answer. So it appears that the result of `card.read()` contains trailing whitespace (probably a newline). – Steven Rumbalski May 23 '17 at 15:24

2 Answers2

1

Try if cards.read().rstrip() == "up" it will definitely solve your problem. rstrip() removes whitespace, newline characters, tab characters, and carrige return characters (\n \t \r respectively) on the tail of a string

Reference:

_TestEthernet method in NetworkTester at https://gist.github.com/portablejim/1985696

Update # 1: Better way to check whether a network interface is up is mentioned here using:

def is_interface_up(interface):
    addr = netifaces.ifaddresses(interface)
    return netifaces.AF_INET in addr
Abdul Rauf
  • 5,798
  • 5
  • 50
  • 70
-1

You could try if cards.read() in ["up"]:

instead of the equals equals which I have had problems with in the past

Jonny M
  • 1
  • 1
  • 1
    Equivalent to `cards.read() in "up"`. Doesn't fix issues with case or whitespace. Perhaps `cards.read().strip().lower() == 'up'`. What would be most helpful is if OP showed us the results of `print(repr(cards.read()))`. Without that we're just guessing at the issue. – Steven Rumbalski May 23 '17 at 14:37
  • Sorry for the negative vote and comment on your first answer. If you edit your answer to something better I'll be happy to change my vote. Just ping me in the comments here. StackOverflow needs helpful people. Please keep answering questions. – Steven Rumbalski May 23 '17 at 14:45