Dev Shed Forums - Python Programming Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language. en Tue, 12 Dec 2017 00:23:21 GMT vBulletin 60 Dev Shed Forums - Python Programming <![CDATA[[Python 3 + FNMatch] PNG Searcher not working... help needed!]]> Mon, 11 Dec 2017 16:32:46 GMT Hey Python Programmers... I try to create an script as an test, thad must be find PNG Files by name... This is my script... Code: --------- # Import fnmatch and os import fnmatch Hey Python Programmers...

I try to create an script as an test, thad must be find PNG Files by name...
This is my script...


# Import fnmatch and os
import fnmatch
import os

# Search PNG-File by Name:
filesearch = input('Search File: ')
for file in os.walk(filesearch):
    if fnmatch.filter(file, '*.png'):

If i call in the name of any PNG Files, this script doesn't works...
No PNG file found wich starts with the first letter you call, they i get on my
computer (laptop)..... I use python 3....

I try to make an PNG-Searcher (or specific file-searcher), they must be find
PNG Files by name (or the png-files they get the same letters)...

If i run my script, no files found with the begin-letters or same names...
I get realy png-files where i get testing it... to look of my script works...

Can anyone give my the just code, so i can expiriment with it...
I am in the learn fase of python (or programming)...

Thanks for my code correction...
Jamie. ]]>
Python Programming JamieVanCadsand
<![CDATA[[Python 3 + Tkinter] Buttons not Showing, help needed!]]> Sun, 10 Dec 2017 19:43:42 GMT Hey Python Programmers... I try to create an GUI they get two or more pages... this is an training... I try to create working with menus and buttons in one script... *This is my script:* Code: --------- # Import Tkinter Hey Python Programmers...

I try to create an GUI they get two or more pages... this is an training...
I try to create working with menus and buttons in one script...

This is my script:

# Import Tkinter
from tkinter import *

# Write my first page
class Window(Frame):

    # Define an __init__
    def __init__(self, master=None):
        # Parameters:
        Frame.__init__(self, master) 

        # Make Master               
        self.master = master

        # Window

    # Create the init_window
    def init_window(self):

        # Changing the Title of my first page

        # The Widget
        self.pack(fill=BOTH, expand=1)

        # Create an Menu
        menu = Menu(self.master)

        # Create an File Object, called File
        file = Menu(menu)
        file.add_command(label="Win Sound", command=self.client_winsound)
        file.add_command(label="Exit", command=self.client_exit)
        menu.add_cascade(label="File", menu=file)

        # Create an File Object, called Edit
        edit = Menu(menu)

        # The Command of Undo in the Edit Tab

        # Edit Cascade
        menu.add_cascade(label="Edit", menu=edit)

    # Define the WinSound Window
    def client_winsound(self):

        # Make the WinSound Window
        class WinSound(Frame):

            # Define the WinSound Init
            def __init_winsound(self, master=None):

                # Called by Frame
                Frame.__init__winsound(self, master)

                # Create it as Master
                self.master = master

                # Called by init_soundplay

            # Define the init_soundplay
            def init_soundplay(self):

                # Change the Title of My Seccond Page

                # Set it as Pack
                self.pack(fill=BOTH, expand=1)

                # Make Button
                self.master.butExit = Button(self, text="WinExit", command=self.__playSystemExit)

            # Define the playSystem button in Working
            def __playSystemExit(self):
                winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

        # Make App-Page2 (My seccond page)
        root1 = Tk()
        app1 = WinSound(root1)
    # Define the Exit
    def client_exit(self):

# Make App-Page Defeult... my first page
rootMain = Tk()
appMain = Window(rootMain)

This is my script... i try to create an app with python and tkinter... This App must be get an
two or more pages... one with an menu, an the seccond page with buttons for play diffrence
WinSounds, this is only an training to get knowledge with python tkinter.... i try to learn this...

But my problem is, thad if you start my seccond page, the play sound button(s) are not showed...
Can anyone correct my code, just it works and the buttons are showed - even they are
working.... If you don't know what my problem is... copy, past and run my script... test my
App and you can see what the problem is... the problem sit in my "WinSound" button in the
File Menu Part in my first page...

This is an test only... not an real app... only i try to learn tkinter.... just i get help needed...

Python Version: Python v3.... Tkinter + WinSound Module...

Can anyone helpme ?...
Thanks, Jamie. ]]>
Python Programming JamieVanCadsand
PNP server code Fri, 01 Dec 2017 16:35:17 GMT I am in need of a python script to run and send responses to a network broadcast on The purpose is to send a url in a sip message to tell a IP phone where the phone's server is located at.

I found the following code for Snom phones. I would prefer that the response would be to ALL subscribe requests using this address/port.


#! /usr/bin/python
# snom multicast telephone discovery
# Author: Filip Polsakiewicz <>
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <>.

import socket
import struct
import sys
import re

from optparse import OptionParser

class snom_phone(object):
    """Basic representation of a snom phone."""

    def __init__(self, mac=None, ip=None, mod=None, fw=None, subs=None):
        """Default constructor."""
        self.mac_addr = mac
        self.ip_addr = ip
        self.sip_port = 5060
        self.model = mod
        self.fw_version = fw
        self.subscribe = subs

    def __repr__(self):
        """Gets a string representation of the phone"""
        return "%s (MAC: %s) running Firmware %s found at IP %s" % (self.model, self.__macrepr(self.mac_addr), self.fw_version, self.ip_addr)

    def __macrepr(self, m):
        """ Normalize a MAC address to lower case unix style """ 
        m = re.sub("[.:-]", "", m)
        m = m.lower()
        n =  "%s:%s:%s:%s:%s:%s" % (m[0:2], m[2:4], m[4:6], m[6:8], m[8:10], m[10:])
        return n

def parse(text):
    """Parses the incoming SUBSCRIBE."""
        lines = text.split('\r\n')
        # Line 1 conatains the SUBSCRIBE and our MAC
        new_phone = atcomtec(subs=text)
        new_phone.mac_addr = lines[0][80:82]
        # We can read the IP address from line 2
        new_phone.ip_addr = lines[1][17:].split(';')[0].split(':')[0]
        new_phone.sip_port = lines[1][17:].split(';')[0].split(':')[1]
        # The other interesting information can be found in line 7
        model_info = lines[6]
        l_model_info = model_info.split(';')
        new_phone.model = l_model_info[3].split('=')[1][1:-1]
        new_phone.fw_version = l_model_info[4].split('=')[1][1:-1]
        print new_phone
        return new_phone
        # Parsing failed. Probably not a SUBSCRIBE
        return None

def get_sip_info(text):
    """Get some relevant SIP information which we need in order to generate the responses."""
    lines = text.split('\r\n')
    # Some SIP info we need
    call_id = lines[4][9:]
    cseq = lines[5][6]
    via_header = lines[1]
    from_header = lines[2]
    to_header = lines[3]
    if options.verbose: print "CallId: " + call_id + "; CSeq: " + cseq + "\r\n";   
    return (call_id, cseq, via_header, from_header, to_header)

def get_ip_address():
        # This is a simple hack to find our IP address
        # AFAIK this is the only platform-independent way to obtain the address

        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('', 0))
            return s.getsockname()[0]

prov_uri = None
parser = OptionParser()
parser.add_option('-u', '--url', action="store", dest="prov_uri", help="URI of the provisioning server")
parser.add_option('-l', '--local-ip', action="store", dest="local_ip", help="Local IP address")
parser.add_option("-v", "--verbose",
                  action="store_true", dest="verbose", default=False,
                  help="make lots of noise")

(options, args) = parser.parse_args()

print "Nimbus PnP Provisioning Server\n"

print "Provisioning URI is %s\n" % options.prov_uri

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', 5060))
mreq = struct.pack('4sl', socket.inet_aton(''), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
if not options.local_ip:
    ip_adr = get_ip_address()
    ip_adr = options.local_ip
print "Local IP Address is :: %s" % ip_adr
print "=" * 80

while True:
    subs = sock.recv(10240)
    if options.verbose: print subs
    phone = parse(subs)
    (call_id, cseq, via_header, from_header, to_header) = get_sip_info(subs)
    if phone:
        # Create a socket to send data
        sendsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sendsock.bind(('%s' % ip_adr, 1036))

            # If a phone has been recognized first send 200 OK
        ok_response = "SIP/2.0 200 OK\r\n"
        ok_response += via_header + "\r\n"
        ok_response += "Contact: <sip:" + phone.ip_addr + ":" + phone.sip_port + ";transport=tcp;handler=dum>\r\n"
        ok_response += to_header + "\r\n"
        ok_response += from_header + "\r\n"
        ok_response += "Call-ID: %s\r\n" % call_id
        ok_response += "CSeq: %s SUBSCRIBE\r\nExpires: 0\r\nContent-Length: 0\r\n" % cseq
        sendsock.sendto(ok_response, ("%s" % phone.ip_addr, int(phone.sip_port)))

        # Now send a NOTIFY with the configuration URL
        if not options.prov_uri:
            prov_uri = ""
            prov_uri = options.prov_uri
            prov_uri = "%s/%s.htm" % (prov_uri,phone.model)

        notify = "NOTIFY sip:%s:%s SIP/2.0\r\n" % (phone.ip_addr, phone.sip_port)
        notify += via_header + "\r\n"
        notify += "Max-Forwards: 20\r\n"
        notify += "Contact: <sip:%s:1036;transport=TCP;handler=dum>\r\n" % ip_adr
        notify += to_header + "\r\n"
        notify += from_header + "\r\n"
        notify += "Call-ID: %s\r\n" % call_id
        notify += "CSeq: 3 NOTIFY\r\n"
        notify += "Content-Type: application/url\r\n"
        notify += "Subscription-State: terminated;reason=timeout\r\n"
        notify += "Event: ua-profile;profile-type=\"device\";vendor=\"OEM\";model=\"OEM\";version=\"7.1.19\"\r\n"
        notify += "Content-Length: %i\r\n" % (len(prov_uri))
        notify += "\r\n%s" % prov_uri

        print "Sending NOTIFY with URI :: %s\n" % prov_uri
        if options.verbose: print notify
        sendsock.sendto(notify, ("%s" % phone.ip_addr, int(phone.sip_port)))

The prov_rui needs to be the local ip of the system the script is running on.

Thanks for any ideas / help anyone can help with. ]]>
Python Programming Edlentz
<![CDATA[NameError: name '__file__' is not defined]]> Tue, 28 Nov 2017 18:47:26 GMT in () 466 467 if __name__ == '__main__': --> 468 test_SdA()]]> HI

I'm getting this error after I run stacked denoising autoencoder code code , how this error can be fixed ?

NameError Traceback (most recent call last)
<ipython-input-9-94013ff577e5> in <module>()
467 if __name__ == '__main__':
--> 468 test_SdA()

<ipython-input-9-94013ff577e5> in test_SdA(finetune_lr, pretraining_epochs, pretrain_lr, training_epochs, dataset, batch_size)
376 print(('The pretraining code for file ' +
--> 377 os.path.split(__file__)[1] +
378 ' ran for %.2fm' % ((end_time - start_time) / 60.)), file=sys.stderr)
379 # end-snippet-4

NameError: name '__file__' is not defined

could you please help me ]]>
Python Programming tohi
Finding the term frequency in a list (new to programming) Fri, 24 Nov 2017 14:51:48 GMT Hi guys

I’m making a ‘term frequency’ program which counts the strings in a list and then gives the number of times the strings have been repeated, for example…


({‘a’: 2, ‘horse’: 2, ‘over’: 1, ‘fast’: 1, ‘duck’: 1, ‘the’: 1, ‘jumps’: 1, ‘smart’: 1})

Here is the code I need to build a function for, the Bag() is an ADT to help the program run.


from Bag import *
terms = ['the','fox','the','quick','fox','jumps','over','the','lazy','dog']
document = Bag()
for term in terms:
def tf(term, document):
print(tf('the', document))

This is what I have as the body at the moment, but I can only get it to count the number of string… How do I divide the string counts by the length of the list to get term frequency?


from collections import Counter
counts = Counter(terms)

Any help is appreciated ]]>
Python Programming Os9008
Please help! Thu, 23 Nov 2017 15:21:21 GMT I want to write this small program in Python:
Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string, printing each letter on a separate line, except backwards.
I tried this:

index = 0
while index < len(fruit):
letter = fruit[index-1]
index = index-1

it works but with an error:

Traceback (most recent call last):
File "/Users/bicharaetienne/Desktop/", line 6, in <module>
letter = fruit[index-1]
IndexError: string index out of range

How can I make it work perfectly?

Thanks! ]]>
Python Programming Bichalways