I am trying to understand the code in :  import socket import sys import time  def get_lock(process_name):     # Without holding a reference to our socket somewhere it gets garbage     # collected when the function exits     get_lock._lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)      try:         get_lock._lock_socket.bind('\0' + process_name)         print 'I got the lock'     except socket.error:         print 'lock exists'         sys.exit()   How do the two lines work which start with get_lock.? It's not like it's a class instance and you are using its methods..
21209
Not many are aware of this feature, but Python's functions (and methods) can have . Behold:  &gt;&gt;&gt; def foo(x): ...     pass ...      &gt;&gt;&gt; foo.score = 10 &gt;&gt;&gt; dir(foo) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name', 'score'] &gt;&gt;&gt; foo.score 10 &gt;&gt;&gt; foo.score += 1 &gt;&gt;&gt; foo.score 11   What are the possible uses and abuses of this feature in Python ? One good use I'm aware of is 's usage of the docstring to associate a syntax rule with a method. But what about custom attributes ? Are there good reasons to use them ?
43330
In python, if I say  print 'h'   I get the letter h and a newline.  If I say   print 'h',   I get the letter h and no newline.  If I say  print 'h', print 'm',   I get the letter h, a space, and the letter m.  How can I prevent Python from printing the space?  The print statements are different iterations of the same loop so I can't just use the + operator.
2152
What exactly are the Python scoping rules?  If I have some code:  code1 class Foo:    code2    def spam.....       code3       for code4..:        code5        x()   Where is x found?  Some possible choices include the list below:   In the enclosing source file In the class namespace In the function definition In the for loop index variable Inside the for loop   Also there is the context during execution, when the function spam is passed somewhere else. And maybe  pass a bit differently?  There must be a simple reference or algorithm somewhere.  It's a confusing world for intermediate Python programmers.
66749
I've read and understood about how you create a daemon process, but from everything I read I never really understood why it needs to be done.  I've read that we do the fork - setsid - fork to avoid the process to gain control of a terminal, but what does this mean ? If I start a program in the background using &amp; (for example './script &amp;' ), what makes this process' execution different than if I ran normally a program that turns itself into a daemon ?  Does this simply mean that if I logout the background process will stop and the daemon will keep running ? I'm really having trouble understanding the 'gain control of a terminal' thing.  The reason this bothers me is because I'm working on an embedded RPi on a robot and I thus need to make programs start on boot. Currently I'm just starting them from rc.local with a command like this su user -c 'python /home/user/launcher.py &amp;' &amp;. I've never had any problem with the program starting on boot (I can even see the process using ps -e when SSHing to the RPi), but I would like to know if there's any risk / if it's bad practice.
18786
I need to lock a file for writing in Python. It will be accessed from multiple Python processes at once. I have found some solutions online, but most fail for my purposes as they are often only Unix based or Windows based.
119943
I'm reading the  function in /init/main.c.  The last function called in start_kernel is rest_init, and at the end of rest_init, cpu_idle is called.   Why is it called as the last function of the start_kernel routine, and what does it do?
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?
116620
What is the most elegant way to solve this:   open a file for reading, but only if it is not already opened for writing open a file for writing, but only if it is not already opened for reading or writing   The built-in functions work like this  &gt;&gt;&gt; path = r"c:\scr.txt" &gt;&gt;&gt; file1 = open(path, "w") &gt;&gt;&gt; print file1 &lt;open file 'c:\scr.txt', mode 'w' at 0x019F88D8&gt; &gt;&gt;&gt; file2 = open(path, "w") &gt;&gt;&gt; print file2 &lt;open file 'c:\scr.txt', mode 'w' at 0x02332188&gt; &gt;&gt;&gt; file1.write("111") &gt;&gt;&gt; file2.write("222") &gt;&gt;&gt; file1.close()   scr.txt now contains '111'.  &gt;&gt;&gt; file2.close()   scr.txt was overwritten and now contains '222' (on Windows, Python 2.4).  The solution should work inside the same process (like in the example above) as well as when another process has opened the file. It is preferred, if a crashing program will not keep the lock open.
113024
If I am evaluating a Python string using eval(), and have a class like:  class Foo(object):     a = 3     def bar(self, x): return x + a   What are the security risks if I do not trust the string? In particular:   Is eval(string, {"f": Foo()}, {}) unsafe? That is, can you reach os or sys or something unsafe from a Foo instance? Is eval(string, {}, {}) unsafe? That is, can I reach os or sys entirely from builtins like len and list? Is there a way to make builtins not present at all in the eval context?   There are some unsafe strings like "[0] * 100000000" I don't care about, because at worst they slow/stop the program. I am primarily concerned about protecting user data external to the program.  Obviously, eval(string) without custom dictionaries is unsafe in most cases.
41393
I've have this socket on my laptop (Lenovo Z570).  What is this port and what is it used for? And what does that symbol mean (I expected a LOCK symbol)?
107129
I'm trying to get a list of processes currently owned by the current user (Environment.UserName). Unfortunately, the Process class doesn't have any way of getting the UserName of the user owning a process.  How do you get the UserName of the user which is the owner of a process using the Process class so I can compare it to Environment.UserName?   If your solution requires a pinvoke, please provide a code example.
85902
I found the following behavior at least weird:  def errors():     try:         ErrorErrorError     finally:         return 10  print errors() # prints: 10 # It should raise: NameError: name 'ErrorErrorError' is not defined   The exception disappears when you use return inside a finally clause. Is that a bug? Is that documented anywhere?  But the real question (and the answer I will mark as correct) is: What is the python developers' reason to allow that odd behavior?
52016
Given a Python object of any kind, is there an easy way to get the list of all methods that this object has?  Or,  if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?
6086
Putting aside whether the use of , I have run into the following conundrum when trying to evaluate isinstance after serializing/deserializing an object via Pickle:  from __future__ import with_statement import pickle  # Simple class definition class myclass(object):     def __init__(self, data):         self.data = data  # Create an instance of the class x = myclass(100)  # Pickle the instance to a file with open("c:\\pickletest.dat", "wb") as f:     pickle.dump(x, f)  # Replace class with exact same definition class myclass(object):     def __init__(self, data):         self.data = data  # Read an object from the pickled file with open("c:\\pickletest.dat", "rb") as f:     x2 = pickle.load(f)  # The class names appear to match print x.__class__ print x2.__class__  # Uh oh, this fails...(why?) assert isinstance(x2, x.__class__)   Can anyone shed some light on why isinstance would fail in this situation? In other words, why does Python think these objects are of two different classes? When I remove the second class definition, isinstance works fine.
19828
I've seen several of answers about using  or , but I would like to be able to find out in my own code (C#) which process is locking a file. I have a nasty feeling that I'm going to have to spelunk around in the win32 API, but if anyone has already done this and can put me on the right track, I'd really appreciate the help. Update Links to similar questions
75794
I've got a bunch of properties which I am going to use read/write locks on. I can implement them either with a try finally or a using clause.  In the try finally I would acquire the lock before the try, and release in the finally. In the using clause, I would create a class which acquires the lock in its constructor, and releases in its Dispose method.  I'm using read/write locks in a lot of places, so I've been looking for ways that might be more concise than try finally. I'm interested in hearing some ideas on why one way may not be recommended, or why one might be better than another.  Method 1 (try finally):  static ReaderWriterLock rwlMyLock_m  = new ReaderWriterLock(); private DateTime dtMyDateTime_m public DateTime MyDateTime {     get     {         rwlMyLock_m .AcquireReaderLock(0);         try         {             return dtMyDateTime_m         }         finally         {             rwlMyLock_m .ReleaseReaderLock();         }     }     set     {         rwlMyLock_m .AcquireWriterLock(0);         try         {             dtMyDateTime_m = value;         }         finally         {             rwlMyLock_m .ReleaseWriterLock();         }     } }   Method 2:  static ReaderWriterLock rwlMyLock_m  = new ReaderWriterLock(); private DateTime dtMyDateTime_m public DateTime MyDateTime {     get     {         using (new ReadLock(rwlMyLock_m))         {             return dtMyDateTime_m;         }     }     set     {         using (new WriteLock(rwlMyLock_m))         {             dtMyDateTime_m = value;         }     } }  public class ReadLock : IDisposable {     private ReaderWriterLock rwl;     public ReadLock(ReaderWriterLock rwl)     {         this.rwl = rwl;         rwl.AcquireReaderLock(0);     }      public void Dispose()     {         rwl.ReleaseReaderLock();     } }  public class WriteLock : IDisposable {     private ReaderWriterLock rwl;     public WriteLock(ReaderWriterLock rwl)     {         this.rwl = rwl;         rwl.AcquireWriterLock(0);     }      public void Dispose()     {         rwl.ReleaseWriterLock();     } }
78279
I'm sure there's a simpler way of doing this that's just not occurring to me.  I'm calling a bunch of methods that return a list.  The list may be empty.  If the list is non-empty, I want to return the first item; otherwise, I want to return None.  This code works:  my_list = get_list() if len(my_list) &gt; 0: return my_list[0] return None   It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it.  Is there?  Edit:  The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this:  x = get_first_list() if x:     # do something with x[0]     # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y:     # do something with y[0]     # inevitably forget the [0] part AGAIN, and have another bug to fix   What I'd like to be doing can certainly be accomplished with a function (and probably will be):  def first_item(list_or_none):     if list_or_none: return list_or_none[0]  x = first_item(get_first_list()) if x:     # do something with x y = first_item(get_second_list()) if y:     # do something with y   I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick.  But seeing these answers, it seems like a function is the simple solution.