The line if __name__ == "__main__": is not working

This is the place for queries that don't fit in any of the other categories.

The line if __name__ == "__main__": is not working

Postby darkcode91 » Thu Jun 13, 2013 10:49 pm

Hello everybody!

I am now starting in python, and I'm following this book "Violent Python -> A cookbook for Hackers, Penetration Testers and Forensic Analyst". I think the book quite interesting and want to learn more about penetrations test and probably make me an expert in security informatics, I think this book is definitely a "must read".

I already have some knowledge of programming but I'm encountering a problem here, in the first exercise book in which the author teaches you program a basic "port scanner". I installed Filezilla to see if it worked and works perfect without functions, but when I start to create functions, such as the low it just runs without error but does not give me the welcome banner server mensage. Basically runs but does not show anything on the console. (By now I'm using Eclipse as IDE)

I'm a bit embarrassed because already search everything on google but not could find a reply to my problem, I think the problem might be in "if __ name__ == __ main__: main ()" but do not even know if it is.

The code is equal to the book. I hope you can help me thanks!





Code: Select all
import socket


def ban (ip, port):
   
       
        socket.setdefaulttimeout(2)
        con=socket.socket()
   
        con.connect ((ip, port))
   
        inf=con.recv(1024)
       
        return inf
   
def main():
   
    ip1="127.0.0.1"
    port=21
   
    ban1= ban(ip1, port)
   
    if ban1:
        print("++"+ ip1 +":"+ str(ban1))
   
    if __name__ == "__main__":
        main()       
Last edited by Yoriz on Thu Jun 13, 2013 11:03 pm, edited 1 time in total.
Reason: Editted the title a bit
darkcode91
 
Posts: 1
Joined: Thu Jun 13, 2013 10:41 pm

Re: [HELP] __name__=="__main__" & 'Def' Functions

Postby Yoriz » Thu Jun 13, 2013 10:56 pm

Hi.
Your indentation is wrong making the last if statement part of the function.
Code: Select all
def main():
   
    ip1="127.0.0.1"
    port=21
   
    ban1= ban(ip1, port)
   
    if ban1:
        print("++"+ ip1 +":"+ str(ban1))
   
    if __name__ == "__main__":
        main()       

Should be
Code: Select all
def main():
   
    ip1="127.0.0.1"
    port=21
   
    ban1= ban(ip1, port)
   
    if ban1:
        print("++"+ ip1 +":"+ str(ban1))
   
if __name__ == "__main__":
    main()       
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 774
Joined: Fri Feb 08, 2013 1:35 am
Location: UK


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests