I am probably missing something really simple.  So here is my code:  def test():     return 'Hello!'  if __name__=="__main__":     print test()   On executing python module_name.py there in no output. When I import the module and execute module_name.test() I get my the expected output. What am I missing here?
3567
Given the following code, what does the if __name__ == "__main__": do?  # Threading example import time, thread  def myfunction(string, sleeptime, lock, *args):     while True:         lock.acquire()         time.sleep(sleeptime)         lock.release()         time.sleep(sleeptime)  if __name__ == "__main__":     lock = thread.allocate_lock()     thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))     thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
53471
Now that it's clear , there is an associated concept that I use all the time without knowing what it really means.   I suppose everybody made once a mistake with parenthesis, resulting  in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __call__ can be used for.  Could you give me some explanations, including examples with the magic method ?
87845
I'm trying to find out how much time it takes to execute a Python statement, so I looked online and found that the standard library provides a module called  that purports to do exactly that:  import timeit  def foo():     # ... contains code I want to time ...  def dotime():     t = timeit.Timer("foo()")     time = t.timeit(1)     print "took %fs\n" % (time,)  dotime()   However, this produces an error:  Traceback (most recent call last):   File "&lt;stdin&gt;", line 1, in &lt;module&gt;   File "&lt;stdin&gt;", line 3, in dotime   File "/usr/local/lib/python2.6/timeit.py", line 193, in timeit     timing = self.inner(it, self.timer)   File "&lt;timeit-src&gt;", line 6, in inner NameError: global name 'foo' is not defined   I'm still new to Python and I don't fully understand all the scoping issues it has, but I don't know why this snippet doesn't work. Any thoughts?
21406
I have a Python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. I want to call the help function on each one. In Ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in Python? eg. something like: from somemodule import foo print(foo.methods)  # or whatever is the correct method to call
27590
states:  Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.  However if the class/method/function that I am importing is only used in rare cases, surely it is more efficient to do the import when it is needed? Isn't this: class SomeClass(object):      def not_often_called(self)         from datetime import datetime         self.datetime = datetime.now()  more efficient than this? from datetime import datetime  class SomeClass(object):      def not_often_called(self)         self.datetime = datetime.now()
36743
Python is quite cool, but unfortunately, its debugger is not as good as perl -d.    One thing that I do very commonly when experimenting with code is to call a function from within the debugger, and step into that function, like so:  # NOTE THAT THIS PROGRAM EXITS IMMEDIATELY WITHOUT CALLING FOO() ~&gt; cat -n /tmp/show_perl.pl 1  #!/usr/local/bin/perl 2 3  sub foo { 4      print "hi\n"; 5      print "bye\n"; 6  } 7 8  exit 0;  ~&gt; perl -d /tmp/show_perl.pl  Loading DB routines from perl5db.pl version 1.28 Editor support available.  Enter h or `h h' for help, or `man perldebug' for more help.  main::(/tmp/show_perl.pl:8):    exit 0;  # MAGIC HAPPENS HERE -- I AM STEPPING INTO A FUNCTION THAT I AM CALLING INTERACTIVELY   DB&lt;1&gt; s foo()  main::((eval 6)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:3): 3:      foo();     DB&lt;&lt;2&gt;&gt; s main::foo(/tmp/show_perl.pl:4):     print "hi\n";     DB&lt;&lt;2&gt;&gt; n hi main::foo(/tmp/show_perl.pl:5):     print "bye\n";     DB&lt;&lt;2&gt;&gt; n bye     DB&lt;2&gt; n Debugged program terminated.  Use q to quit or R to restart,   use O inhibit_exit to avoid stopping after program termination,   h q, h R or h O to get additional info.      DB&lt;2&gt; q   This is incredibly useful when trying to step through a function's handling of various different inputs to figure out why it fails.  However, it does not seem to work in either pdb or pydb (I'd show an equivalent python example to the one above but it results in a large exception stack dump).  So my question is twofold:   Am I missing something? Is there a python debugger that would indeed let me do this?   Obviously I could put the calls in the code myself, but I love working interactively, eg. not having to start from scratch when I want to try calling with a slightly different set of arguments.
4439
If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again?  For example: I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so  import MyLib ReallyBigLib = MyLib.SomeModule.ReallyBigLib   or just  import MyLib import ReallyBigLib
29326
Here is my test code and picture:  import bpy   # Simple property reading/writing from ID properties. # This is what the RNA would do internally. def get_float(self):     return self["testprop"]   def set_float(self, value):     self["testprop"] = value  #bpy.types.Scene.test_float = bpy.props.FloatProperty(get=get_float,set=set_float) bpy.types.Scene.test_float = bpy.props.FloatProperty()   bpy.context.scene.test_float = 12.34     When I don't explicitly set the "get/set" function for my property, after assigning the value, I can get the property value by 'scene["test_float"]', but if I explicitly set the "get/set" function, then if I try to type in the same commands, I will receive a error "KeyError: 'bpy_struct[key]: key "test_float" not found'" . So what should I do to get the same results by using explicitly  "get/set" function?
2713
I wrote a simple program to print "hello world". The compiler shows a message "Compilation finished successfully". But the out put of the program, I can't see anywhere.    As using codeblocks a new terminal comes out with the program output. How can I see the program output using geany compiler.
13296
I don't want to use /Application.../blender -P my_script.py but I want to tell a running Blender process to execute a script.   Is there an existing method to tell a running Blender process to execute a python script?  For example using http://localhost:123/run_script=myscript.py
1022
The following code works as expected in both Python 2.5 and 3.0:  a, b, c = (1, 2, 3)  print(a, b, c)  def test():     print(a)     print(b)     print(c)    # (A)     #c+=1       # (B) test()   However, when I uncomment line (B), I get an UnboundLocalError: 'c' not assigned at line (A). The values of a and b are printed correctly. This has me completely baffled for two reasons:   Why is there a runtime error thrown at line (A) because of a later statement on line (B)? Why are variables a and b printed as expected, while c raises an error?   The only explanation I can come up with is that a local variable c is created by the assignment c+=1, which takes precedent over the "global" variable c even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists.  Could someone please explain this behavior?
108395
All I wrote in the interpreter was as follows:  &gt;&gt;&gt; print "Hello, World!"   File "&lt;stdin&gt;", line 1     print "Hello, World!"                         ^ SyntaxError: invalid syntax   How did I even get an error? All I tried to do was run a print command.
7325
How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.
53222
I am executing every now and then some python scripts which take quite long to execute.  I execute them like this: $ time python MyScript.py  How can I play a sound as soon as the execution of the script is done?  I use Ubuntu 10.10 (Gnome desktop).
3114
I'd like to do it in Python. What I'd like to do in this example in C: #include &lt;stdio.h&gt;  int main() {     int i;     for (i=0; i&lt;10; i++) printf(&quot;.&quot;);     return 0; }  Output: ..........  In Python: &gt;&gt;&gt; for i in range(10): print('.') . . . . . . . . . . &gt;&gt;&gt; print('.', '.', '.', '.', '.', '.', '.', '.', '.', '.') . . . . . . . . . .  In Python print will add a \n or space, how can I avoid that? Now, it's just an example, don't tell me I can first build a string then print it. I'd like to know how to &quot;append&quot; strings to stdout.
7012
In Python 2.5, the following code raises a TypeError:  &gt;&gt;&gt; class X:       def a(self):         print "a"  &gt;&gt;&gt; class Y(X):       def a(self):         super(Y,self).a()         print "b"  &gt;&gt;&gt; c = Y() &gt;&gt;&gt; c.a() Traceback (most recent call last):   File "&lt;stdin&gt;", line 1, in &lt;module&gt;   File "&lt;stdin&gt;", line 3, in a TypeError: super() argument 1 must be type, not classobj   If I replace the class X with class X(object), it will work. What's the explanation for this?
13167
In Python, is there a portable and simple way to test if an executable program exists?  By simple I mean something like the which command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with Popen &amp; al and see if it fails (that's what I'm doing now, but imagine it's launchmissiles)