473,326 Members | 2,111 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Starting Python... some questions

I started using Python a couple of days ago - here are a few
questions:

* Doesn't the __main__() method automatically execute when I run my
python program?
* Only when I do an import of my test.py file within python and then
run test.__main__() I can see where my bugs are. Is this correct?
(right now this is my only way of running my python program and see
where I have problems)
* Once I've done an import and then I wish to make a change to the
file I've imported I have to quit Python, restart and import that
module again in order for the module to be refreshed. Is there no "re-
import" ?
* Finally, could someone tell me why I'm having problems with the
small module below?
- Python pretends I provide chassis_id() with three parameters, even
though I clearly only provide it with two - why?

Thanks!

#!/usr/bin/python
import scapy
import struct

class lldp_class:
def __init__(self):
self.chassis_id_tlv = None

def chassis_id(subtype, chassis_info):
if subtype == 4:
chassis_data = struct.pack("!B",chassis_info)
subtype_data = struct.pack("!B",subtype)
self.chassis_id_tlv = subtype_data + chassis_data

def __main__():
p = lldp_class()
p.chassis_id(4, "01:80:C2:00:00:0E")
payload = p.chassis_id_tlv
ether = scapy.Ether(dst="01:02:03:04:05:06")
fullpayload = ether + payload
sendp(fullpayload)

Mar 13 '07 #1
9 1725
je*********@yahoo.com wrote:
I started using Python a couple of days ago - here are a few
questions:

* Doesn't the __main__() method automatically execute when I run my
python program?
* Only when I do an import of my test.py file within python and then
run test.__main__() I can see where my bugs are. Is this correct?
(right now this is my only way of running my python program and see
where I have problems)
No, there is no special __main__ function, to the best of my knowledge.
I think the idiom you're thinking of is:

if __name__="__main__":
#Your main stuff here

But that won't execute if you do an import. Only when you call the
script directly, like:

python myscript.py

for example.
* Once I've done an import and then I wish to make a change to the
file I've imported I have to quit Python, restart and import that
module again in order for the module to be refreshed. Is there no "re-
import" ?
There is. The reload command. Usage is similar to import:

import MyModule
#Do your edit, and reload thusly:
reload MyModule
* Finally, could someone tell me why I'm having problems with the
small module below?
- Python pretends I provide chassis_id() with three parameters, even
though I clearly only provide it with two - why?
Python expects self as the first parameter. You might want to take
another look at the class bits of your tutorial of choice, or:
http://docs.python.org/tut/node11.html

The function definition should look more like:

def chassis_id(self, subtype, chassis_info):

HTH.
-Jordan Greenberg
Mar 13 '07 #2
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

je*********@yahoo.com wrote:
I started using Python a couple of days ago - here are a few
questions:

* Doesn't the __main__() method automatically execute when I run my
python program?
* Only when I do an import of my test.py file within python and then
run test.__main__() I can see where my bugs are. Is this correct?
(right now this is my only way of running my python program and see
where I have problems)
* Once I've done an import and then I wish to make a change to the
file I've imported I have to quit Python, restart and import that
module again in order for the module to be refreshed. Is there no "re-
import" ?
* Finally, could someone tell me why I'm having problems with the
small module below?
- Python pretends I provide chassis_id() with three parameters, even
though I clearly only provide it with two - why?
No, Python is executing a module. You should explicit call __main__()
at top scope of
your module. For ex.

if __name__ == '__main__':
__main__()

This snippet calls __main__() when the module is executed directly,
but not imported as a module.

Once a module had been imported, you should invoke reload() function
to reload it from filesystem.
- --
Thinker Li - th*****@branda.to th********@gmail.com
http://heaven.branda.to/~thinker/GinGin_CGI.py
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (FreeBSD)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFF9i/j1LDUVnWfY8gRAgidAKCxHUWf/XTuT8fRQmeL3hnsO4fohQCgt27R
jCNoz4hgp2CxD7H5HPwkfgM=
=4g/m
-----END PGP SIGNATURE-----

Mar 13 '07 #3
On Mon, 12 Mar 2007 21:39:11 -0700, jezonthenet wrote:
I started using Python a couple of days ago - here are a few
questions:

* Doesn't the __main__() method automatically execute when I run my
python program?

No.

* Only when I do an import of my test.py file within python and then
run test.__main__() I can see where my bugs are. Is this correct?
(right now this is my only way of running my python program and see
where I have problems)
That's a good way of choosing to run __main__ manually, but there are
other ways.

If you add a line to the end of your program:

__main__()
the function will be executed whenever the program runs. That is both when
you import it, and when you run it from the command line.

To ensure it doesn't run when you import, do this:
if __name__ == "__main__":
__main__()
* Once I've done an import and then I wish to make a change to the
file I've imported I have to quit Python, restart and import that
module again in order for the module to be refreshed. Is there no "re-
import" ?
Yes there is. Do this:

import my_module
# do things
# edit the file
# don't forget to save changes (that always catches me out)
reload(my_module)

* Finally, could someone tell me why I'm having problems with the
small module below?
- Python pretends I provide chassis_id() with three parameters, even
though I clearly only provide it with two - why?

Thanks!

#!/usr/bin/python
import scapy
import struct

class lldp_class:
def __init__(self):
self.chassis_id_tlv = None

def chassis_id(subtype, chassis_info):
if subtype == 4:
chassis_data = struct.pack("!B",chassis_info)
subtype_data = struct.pack("!B",subtype)
self.chassis_id_tlv = subtype_data + chassis_data
Class methods always take a first parameter that points to the
class instance. By convention, it should be called "self". So you should
write this as:

def chassis_id(self, subtype, chassis_info):
if subtype == 4:
chassis_data = struct.pack("!B",chassis_info)
subtype_data = struct.pack("!B",subtype)
self.chassis_id_tlv = subtype_data + chassis_data
When you call the method:

my_instance = lldp_class()
my_instance.chassis_id(4, "01:80:C2:00:00:0E")

Python automatically fills in a reference to the instance and calls this:

lldp_class.chassis_id(my_instance, 4, "01:80:C2:00:00:0E")
Just remember to always put "self" as the first argument to a class
method, and you will (almost never) go wrong!

--
Steven D'Aprano

Mar 13 '07 #4
Jo****@bag.python.org, "Greenberg <"@bag.python.org, "greenbergj\""@NOSPAM.xs4all.nl, wi*****@bag.python.org, ">"@bag.python.org writes:
je*********@yahoo.com wrote:
* Doesn't the __main__() method automatically execute when I run
my python program?

No, there is no special __main__ function, to the best of my
knowledge.
Guido van Rossum has mused on the idiom of the 'main' function in modules:

<URL:http://www.artima.com/weblogs/viewpost.jsp?thread=4829>

My idiom for this is:

=====
def __main__(argv=None):
""" Mainline code for this program """

from sys import argv as sys_argv
if argv is None:
argv = sys_argv

foo = Foo(argv) # Foo is the main thing I need
exitcode = None
try:
foo.do_the_main_thing()
except SystemExit, e:
exitcode = e.code

return exitcode

if __name__ == "__main__":
import sys
exitcode = __main__(argv=sys.argv)
sys.exit(exitcode)
=====

The reason for the local 'sys' imports is that I can boilerplate this
code and not have to worry about whether the rest of the program
actually uses the 'sys' module.

The reason for parameterising 'argv', but defaulting it to the system
argv, is that I can unit-test the '__main__' function
programmatically, while still letting it pick up the real argv when
the program is run.

Same reason for catching SystemExit, and then going on to call
'sys.exit()' myself: it allows the __main__ function to be unit-tested
easily, while still letting me use 'sys.exit()' in my application code
whenever it makes sense.

Now, when I write unit tests for my program (i.e. a Python module
designed to be run as a command), it can still be imported safely into
my unit tests, and all the code gets covered by test cases except the
three-line stanza at the end.
Htag.pl 0.0.23 - Simon Huggins <hu****@earth.li Released under GPL
Copyright (C) 1999-2002 Project Purple. http://www.earth.li/projectpurple/

Got sigmatch == ^/home/bignose/\.sigs/news.*$

--
\ "The right to search for truth implies also a duty; one must |
`\ not conceal any part of what one has recognized to be true." |
_o__) -- Albert Einstein |
Ben Finney

Mar 13 '07 #5
Ben Finney <bi****************@benfinney.id.auwrites:
Now, when I write unit tests for my program (i.e. a Python module
designed to be run as a command), it can still be imported safely
into my unit tests, and all the code gets covered by test cases
except the three-line stanza at the end.
All I need now is for Python to automatically execute a '__main__'
function if the module name is '__main__' (which it seems the OP
expected should happen), and unit test coverage could be 100% :-)
Htag.pl 0.0.23 - Simon Huggins <hu****@earth.li Released under GPL
Copyright (C) 1999-2002 Project Purple. http://www.earth.li/projectpurple/

Got sigmatch == ^/home/bignose/\.sigs/news.*$
Er, okay. That was a bit strange. Sorry for the flubbed sigmonster.

--
\ "I bet one legend that keeps recurring throughout history, in |
`\ every culture, is the story of Popeye." -- Jack Handey |
_o__) |
Ben Finney

Mar 13 '07 #6
You only need three things here:

je*********@yahoo.com wrote:
>
#!/usr/bin/python
import scapy
import struct

class lldp_class:
def __init__(self):
self.chassis_id_tlv = None

def chassis_id(subtype, chassis_info):
Make that
def chassis_id(self, subtype, chassis_info):

When you call "p.chassis_id", "p" is passed as the first parameter to
chassis_id. By convention, we call that "self", in the same way the object
of a C++ method is called "this" (although that is enforced, rather than
convention).
> if subtype == 4:
chassis_data = struct.pack("!B",chassis_info)
subtype_data = struct.pack("!B",subtype)
self.chassis_id_tlv = subtype_data + chassis_data

def __main__():
Make that
def main():

The underscores have a special meaning that you do not need here. Note
that the name "main" is not required; some people call it something like
"test".
> p = lldp_class()
p.chassis_id(4, "01:80:C2:00:00:0E")
payload = p.chassis_id_tlv
ether = scapy.Ether(dst="01:02:03:04:05:06")
fullpayload = ether + payload
sendp(fullpayload)
Now, at the end, add:

if __name__=="__main__":
main()

That should do it.
--
Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Mar 13 '07 #7
je*********@yahoo.com a écrit :
I started using Python a couple of days ago - here are a few
questions:

* Doesn't the __main__() method automatically execute when I run my
python program?
Which "__main__" method ???

Anyway, the answer is no. Every code at the top-level (which includes
import, class and def statements...) is executed when the module is
first loaded - whether as a proper module (ie: imported from somewhere
else) or as a main program (ie-python mymodule.py). In the first case,
the special variable __name__ is set to the module's name, in the second
to '__main__'. So you can rely on this to have code executed when the
module is used as a program. The usual idiom is

# mymodule.py
(imports here)
(classes and defs here)

def main(argv):
(code of main function here)
return 0

if __name__ == '__main__':
import sys
sys.exit(main(sys.argv))

* Only when I do an import of my test.py file within python and then
run test.__main__()
BTW, you should *not* use names with 2 leadings and 2 trailing
underscores. These names are reserved for Python implementation stuff.
I can see where my bugs are. Is this correct?
Nope. You can also spot bugs by reading the code or running it thru the
debugger !-)

More seriously : using the above idiom (or any variant of - the
important part being the conditional on __name__ == '__main__'), you can
just
$ python mymodule.py

to run your program.
(right now this is my only way of running my python program and see
where I have problems)
* Once I've done an import and then I wish to make a change to the
file I've imported I have to quit Python, restart and import that
module again in order for the module to be refreshed. Is there no "re-
import" ?
reload(module_object)

But it's of very limited use. The best thing to do is usually to have a
simple test file that setup the desired state (imports etc) that you
execute after each change, passing the -i option to the python
interpreter (this will leave the interpreter in interactive mode after
execution of the test file, so you can inspect your objects, test things
etc).
* Finally, could someone tell me why I'm having problems with the
small module below?
- Python pretends I provide chassis_id() with three parameters, even
though I clearly only provide it with two - why?
Without even reading the code, I can tell you it's an instance or
classmethod with either a wrong declaration or wrongly called.
>
#!/usr/bin/python
import scapy
import struct

class lldp_class:
Do yourself a favor: use new-style classes. Also, it would be better to
stick to usual naming conventions (Python relies heavily on conventions):
http://www.python.org/dev/peps/pep-0008/

class Lldp(object):
def __init__(self):
self.chassis_id_tlv = None

def chassis_id(subtype, chassis_info):
Bingo. You need to have self as the first argument. The instance is
passed as the first argument of a method.

def chassis_id(self, subtype, chassis_info):
if subtype == 4:
chassis_data = struct.pack("!B",chassis_info)
subtype_data = struct.pack("!B",subtype)
self.chassis_id_tlv = subtype_data + chassis_data

def __main__():

def main():
p = lldp_class()
p.chassis_id(4, "01:80:C2:00:00:0E")
For the record: this is interpreted as:
lldp_class.chassis_id(p, 4, "01:80:C2:00:00:0E")

payload = p.chassis_id_tlv
ether = scapy.Ether(dst="01:02:03:04:05:06")
fullpayload = ether + payload
sendp(fullpayload)
if __name__ == '__main__':
main()

As a side note, it looks like there are a couple point where your design
may be improved. Like passing subtype and chassis_info to the __init__
of your class.

HTH
Mar 13 '07 #8
Steven D'Aprano a écrit :
On Mon, 12 Mar 2007 21:39:11 -0700, jezonthenet wrote:
>I started using Python a couple of days ago - here are a few
questions:

* Doesn't the __main__() method automatically execute when I run my
python program?


No.

>* Only when I do an import of my test.py file within python and then
run test.__main__() I can see where my bugs are. Is this correct?
(right now this is my only way of running my python program and see
where I have problems)

That's a good way of choosing to run __main__ manually, but there are
other ways.

If you add a line to the end of your program:

__main__()
the function will be executed whenever the program runs. That is both when
you import it, and when you run it from the command line.

To ensure it doesn't run when you import, do this:
if __name__ == "__main__":
__main__()
>* Once I've done an import and then I wish to make a change to the
file I've imported I have to quit Python, restart and import that
module again in order for the module to be refreshed. Is there no "re-
import" ?

Yes there is. Do this:

import my_module
# do things
# edit the file
# don't forget to save changes (that always catches me out)
reload(my_module)

>* Finally, could someone tell me why I'm having problems with the
small module below?
- Python pretends I provide chassis_id() with three parameters, even
though I clearly only provide it with two - why?

Thanks!

#!/usr/bin/python
import scapy
import struct

class lldp_class:
def __init__(self):
self.chassis_id_tlv = None

def chassis_id(subtype, chassis_info):
if subtype == 4:
chassis_data = struct.pack("!B",chassis_info)
subtype_data = struct.pack("!B",subtype)
self.chassis_id_tlv = subtype_data + chassis_data

Class methods
s/Class/Instance/

classmethods are methods that takes the class as first parameter.
always take a first parameter that points to the
class instance.
(snip)
Just remember to always put "self" as the first argument to a class
method,
idem.
Mar 13 '07 #9
Ben Finney wrote:
Ben Finney <bi****************@benfinney.id.auwrites:
>Now, when I write unit tests for my program (i.e. a Python module
designed to be run as a command), it can still be imported safely
into my unit tests, and all the code gets covered by test cases
except the three-line stanza at the end.

All I need now is for Python to automatically execute a '__main__'
function if the module name is '__main__' (which it seems the OP
expected should happen), and unit test coverage could be 100% :-)
Short hint to go further:
exec file('/usr/lib/python2.4/timeit.py') in {'__name__': '__main__'}

nd
Mar 13 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: RosalieM | last post by:
I would like to understand what python needs to work on unix. And to understand how i can make it smalest possible? I dont understand at all setup. I searched in python.org and in sources but it...
4
by: Skip Montanaro | last post by:
(moving over from webmaster mailbox) scott> I'm sorry for bothering you, but I've tried to post to the Python scott> Tutor Mail List, tried to get someone from Bay PIggies to scott> respond, but...
114
by: Maurice LING | last post by:
This may be a dumb thing to ask, but besides the penalty for dynamic typing, is there any other real reasons that Python is slower than Java? maurice
3
by: Alessandro Brollo | last post by:
Far from a professional programmer, I'm simply a newbie Python user. Two basic questions: 1. I don't want to post banal questions about Python to main Python list. Does a "banal Python questions...
8
by: Ilias Lazaridis | last post by:
Where can I find practical coding examples for real life coding problems? Something like a categorized solution guide? - My current problem: * create a folder * seems to be:...
19
by: Ahmer | last post by:
Hi all! I am a 15 year old High School Sophomore. I would like to start programming in Python. In school, we are learning Java (5) and I like to use the Eclipse IDE, I also am learning PHP as...
8
by: Krypto | last post by:
Hi, I have used Python for a couple of projects last year and I found it extremely useful. I could write two middle size projects in 2-3 months (part time). Right now I am a bit rusty and trying...
4
by: durumdara | last post by:
Hi! My problem is that: The "test.py" is working in every machine that I use except in my home machine. Formerly it worked but now not. I don't know what happened, I searching for some...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.