Python - Problem mit Exception



  • ich versuche diesen Code hier mit Python3.2 zum Laufen zu bekommen:

    import ping, socket
    try:
        ping.verbose_ping('www.google.com', run=3)
        delay = ping.Ping('www.wikipedia.org', timeout=2000).do()
    except socket.error, e:
        print "Ping Error:", e
    

    beim Ausführen kommt folgende Fehlermeldung:

    C:\USB\dev>ping.py
      File "C:\USB\dev\ping.py", line 5
        except socket.error, e:
                           ^
    SyntaxError: invalid syntax
    

    was muss ich ändern? (bin neu bei Python)



  • except socket.error as e

    Die Syntax hat sich mit Python 3.0 geändert.



  • habs jetzt so geändert:

    import ping, socket
    try:
        ping.verbose_ping('www.google.com', run=3)
        delay = ping.Ping('www.wikipedia.org', timeout=2000).do()
    except socket.error as e:
        print ("Ping Error:", e)
    

    jetzt habe ich diesen Fehler:

    C:\USB\dev>ping.py
    Traceback (most recent call last):
      File "C:\USB\dev\ping.py", line 1, in <module>
        import ping, socket
      File "C:\USB\dev\ping.py", line 3, in <module>
        ping.verbose_ping('www.google.com', run=3)
    AttributeError: 'module' object has no attribute 'verbose_ping'
    

    ich kann leider nicht die Dokumentation des ping moduls finden
    hab hier gesucht: http://docs.python.org/py3k/library/
    kann man irgendwo nach sehen welche Methoden die pink Klasse anbietet?



  • Ich mag mich irren, aber wenn du dein Script 'ping.py' nennst und 'import ping' schreibst, importierst du dann nicht dein Script statt des ping-Moduls?



  • du hast recht. Ich dachte immer ping wäre eine Klasse - aber das ist ein Modul

    ich verwende jetzt dieses ping modul: https://github.com/jedie/python-ping/blob/master/ping.py

    und mein script heißt jetzt ping_test und sieht so aus:

    import ping, socket
    try:
        ping.verbose_ping('www.google.com', run=3)
        delay = ping.Ping('www.wikipedia.org', timeout=2000).do()
    except socket.error as e:
        print ("Ping Error:", e)
    

    Jetzt kommt folgender Fehler

    C:\USB\dev>ping_test.py
    Traceback (most recent call last):
      File "C:\USB\dev\ping_test.py", line 1, in <module>
        import ping, socket
      File "C:\USB\dev\ping.py", line 226
        except socket.error, (errno, msg):
                           ^
    SyntaxError: invalid syntax
    

    wenn ich darauß ein socket.error as (errno, msg): mache kommt lieder immer noch ein Fehler



  • mache kommt lieder immer noch ein Fehler

    Nach Analyse der Fehlermeldung kommt nur eine Ursache in Betracht: Division through zero.



  • Ethon schrieb:

    Nach Analyse der Fehlermeldung kommt nur eine Ursache in Betracht: Division through zero.

    Ja. Jedenfalls auf keinen Fall derselbe Fehler wie im Anfangsposting. Da hätte man ja nicht nochmal fragen müssen :p

    BTW ist C:\USB\dev\ping.py dieses Modul? Dann ist das wohl nicht Python 3.x-tauglich.



  • Bashar schrieb:

    except socket.error as e

    Die Syntax hat sich mit Python 3.0 geändert.

    ... nicht derselbe Fehler wieder??



  • hab hier jetzt einen python 3.2 port gefunden: http://www.g-loaded.eu/2009/10/30/python-ping/

    aber anscheinend hat das HTML Formatting etwas zerschossen - z. B. Zeile 108 if countTo> 16) + (sum & 0xffff) - was wollte der da machen?:

    #!/usr/bin/env python
    
    """
        A pure python ping implementation using raw socket.
    
        Note that ICMP messages can only be sent from processes running as root.
    
        Derived from ping.c distributed in Linux's netkit. That code is
        copyright (c) 1989 by The Regents of the University of California.
        That code is in turn derived from code written by Mike Muuss of the
        US Army Ballistic Research Laboratory in December, 1983 and
        placed in the public domain. They have my thanks.
    
        Bugs are naturally mine. I'd be glad to hear about them. There are
        certainly word - size dependenceies here.
    
        Copyright (c) Matthew Dixon Cowles, .
        Distributable under the terms of the GNU General Public License
        version 2. Provided with no warranties of any sort.
    
        Original Version from Matthew Dixon Cowles:
          -> ftp://ftp.visi.com/users/mdc/ping.py
    
        Rewrite by Jens Diemer:
          -> http://www.python-forum.de/post-69122.html#69122
    
        Rewrite by George Notaras:
          -> http://www.g-loaded.eu/2009/10/30/python-ping/
    
        Revision history
        ~~~~~~~~~~~~~~~~
    
        August 3, 2011
        --------------
        Ported to py3k by Zach Ware. Mostly done by 2to3; also minor changes to
        deal with bytes vs. string changes (no more ord() in checksum() because
        >source_string< is actually bytes, added .encode() to data in
        send_one_ping()).  That's about it.
    
        November 8, 2009
        ----------------
        Improved compatibility with GNU/Linux systems.
    
        Fixes by:
         * George Notaras -- http://www.g-loaded.eu
        Reported by:
         * Chris Hallman -- http://cdhallman.blogspot.com
    
        Changes in this release:
         - Re-use time.time() instead of time.clock(). The 2007 implementation
           worked only under Microsoft Windows. Failed on GNU/Linux.
           time.clock() behaves differently under the two OSes[1].
    
        [1] http://docs.python.org/library/time.html#time.clock
    
        May 30, 2007
        ------------
        little rewrite by Jens Diemer:
         -  change socket asterisk import to a normal import
         -  replace time.time() with time.clock()
         -  delete "return None" (or change to "return" only)
         -  in checksum() rename "str" to "source_string"
    
        November 22, 1997
        -----------------
        Initial hack. Doesn't do much, but rather than try to guess
        what features I (or others) will want in the future, I've only
        put in what I need now.
    
        December 16, 1997
        -----------------
        For some reason, the checksum bytes are in the wrong order when
        this is run under Solaris 2.X for SPARC but it works right under
        Linux x86. Since I don't know just what's wrong, I'll swap the
        bytes always and then do an htons().
    
        December 4, 2000
        ----------------
        Changed the struct.pack() calls to pack the checksum and ID as
        unsigned. My thanks to Jerome Poincheval for the fix.
    
        Last commit info:
        ~~~~~~~~~~~~~~~~~
        $LastChangedDate: $
        $Rev: $
        $Author: $
    """
    
    import os, sys, socket, struct, select, time
    
    # From /usr/include/linux/icmp.h; your milage may vary.
    ICMP_ECHO_REQUEST = 8 # Seems to be the same on Solaris.
    
    def checksum(source_string):
        """
        I'm not too confident that this is right but testing seems
        to suggest that it gives the same answers as in_cksum in ping.c
        """
        sum = 0
        countTo = (len(source_string)/2)*2
        count = 0
        while count<countTo:
            thisVal = source_string[count + 1]*256 + source_string[count]
            sum = sum + thisVal
            sum = sum & 0xffffffff # Necessary?
            count = count + 2
    
        if countTo> 16)  +  (sum & 0xffff)
        sum = sum + (sum >> 16)
        answer = ~sum
        answer = answer & 0xffff
    
        # Swap bytes. Bugger me if I know why.
        answer = answer >> 8 | (answer << 8 & 0xff00)
    
        return answer
    
    def receive_one_ping(my_socket, ID, timeout):
        """
        receive the ping from the socket.
        """
        timeLeft = timeout
        while True:
            startedSelect = time.time()
            whatReady = select.select([my_socket], [], [], timeLeft)
            howLongInSelect = (time.time() - startedSelect)
            if whatReady[0] == []: # Timeout
                return
    
            timeReceived = time.time()
            recPacket, addr = my_socket.recvfrom(1024)
            icmpHeader = recPacket[20:28]
            type, code, checksum, packetID, sequence = struct.unpack(
                "bbHHh", icmpHeader
            )
            if packetID == ID:
                bytesInDouble = struct.calcsize("d")
                timeSent = struct.unpack("d", recPacket[28:28 + bytesInDouble])[0]
                return timeReceived - timeSent
    
            timeLeft = timeLeft - howLongInSelect
            if timeLeft dest_addrcountdest_addrtimeout< and display
        the result.
        """
        for i in range(count):
            print("ping %s..." % dest_addr, end=' ')
            try:
                delay  =  do_one(dest_addr, timeout)
            except socket.gaierror as e:
                print("failed. (socket error: '%s')" % e.args[1])
                break
    
            if delay  ==  None:
                print("failed. (timeout within %ssec.)" % timeout)
            else:
                delay  =  delay * 1000
                print("get ping in %0.4fms" % delay)
        print()
    
    if __name__ == '__main__':
        verbose_ping("heise.de")
        verbose_ping("google.com")
        verbose_ping("a-test-url-taht-is-not-available.com")
        verbose_ping("localhost")
    


  • HTML-Formatierung? Sieht doch ganz ordentlich aus (C&P von der von dir verlinkten Seite).

    def checksum(source_string):
        """
        I'm not too confident that this is right but testing seems
        to suggest that it gives the same answers as in_cksum in ping.c
        """
        sum = 0
        countTo = (len(source_string)/2)*2
        count = 0
        while count<countTo:
            thisVal = ord(source_string[count + 1])*256 + ord(source_string[count])
            sum = sum + thisVal
            sum = sum & 0xffffffff # Necessary?
            count = count + 2
    
        if countTo<len(source_string):  # <--------------------------- Line 108
            sum = sum + ord(source_string[len(source_string) - 1])
            sum = sum & 0xffffffff # Necessary?
    
        sum = (sum >> 16)  +  (sum & 0xffff)
        sum = sum + (sum >> 16)
        answer = ~sum
        answer = answer & 0xffff
    
        # Swap bytes. Bugger me if I know why.
        answer = answer >> 8 | (answer << 8 & 0xff00)
    
        return answer
    


  • Zeile 108 ist die hier: if countTo> 16) + (sum & 0xffff)
    da geht eine Klammer nach der 16 auf - wo soll die dazugehören? außerdem müsste nach dem if doch irgendwann ein ":" kommen

    ich überlege gerade ob ich das nicht mit boost und C++ schneller schaffe - ich will nur google.de pingen um festzustellen ob noch eine Internetverbindung vorhanden ist



  • Jetzt mal im Ernst, bei dem Zeitaufwand für eine popelige Aufgabe steht doch Kosten und Nutzen in keinerlei Relation mehr. Nimm doch einfach urlopen und ruf die Startseite ab.



  • Mops324 schrieb:

    Zeile 108 ist die hier: if countTo> 16) + (sum & 0xffff)

    Oder auch die mit der 108 davor 🙄 Der Quelltext ist auf der Seite richtig, ich hab dir doch den angeblich fehlerhaften Ausschnitt gerade gepostet. Ich weiß nicht, was du gemacht hast, um ihn kaputtzukriegen.



  • Letztendlich habe ich jetzt ein ping programm mithilfe von C++ und Boost programmiert. Dies hat zwar auch 3h gedauert aber genau soviel Zeit habe ich auch in Python Lösung investiert, die leider nicht funktioniert hat (programmiere überhaupt nicht mit python aber sehr viel mit C++)


Anmelden zum Antworten