title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
1,429,154
<p>Another way:</p> <pre><code>import math def hextobinary(hex_string): s = int(hex_string, 16) num_digits = int(math.ceil(math.log(s) / math.log(2))) digit_lst = ['0'] * num_digits idx = num_digits while s &gt; 0: idx -= 1 if s % 2 == 1: digit_lst[idx] = '1' s = s / 2 return ''.join(digit_lst) print hextobinary('abc123efff') </code></pre>
2
2009-09-15T19:24:01Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
1,519,418
<p>hex --> decimal then decimal --> binary</p> <pre><code>#decimal to binary def d2b(n): bStr = '' if n &lt; 0: raise ValueError, "must be a positive integer" if n == 0: return '0' while n &gt; 0: bStr = str(n % 2) + bStr n = n &gt;&gt; 1 return bStr #hex to binary def h2b(hex): return d2b(int(hex,16)) </code></pre>
3
2009-10-05T11:00:55Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
4,859,937
<p>For solving the left-side trailing zero problem:</p> <hr> <pre><code>my_hexdata = "1a" scale = 16 ## equals to hexadecimal num_of_bits = 8 bin(int(my_hexdata, scale))[2:].zfill(num_of_bits) </code></pre> <hr> <p>It will give 00011010 instead of the trimmed version.</p>
58
2011-02-01T07:17:53Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
7,373,476
<p>This is a slight touch up to Glen Maynard's solution, which I think is the right way to do it. It just adds the padding element.</p> <pre><code> def hextobin(self, hexval): ''' Takes a string representation of hex data with arbitrary length and converts to string representation of binary. Includes padding 0s ''' thelen = len(hexval)*4 binval = bin(int(hexval, 16))[2:] while ((len(binval)) &lt thelen): binval = '0' + binval return binval </code></pre> <p>Pulled it out of a class. Just take out <code>self, </code> if you're working in a stand-alone script.</p>
5
2011-09-10T17:44:44Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
9,486,791
<pre><code>"{0:020b}".format(int('ABC123EFFF', 16)) </code></pre>
11
2012-02-28T17:28:51Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
9,686,905
<pre><code>no=raw_input("Enter your number in hexa decimal :") def convert(a): if a=="0": c="0000" elif a=="1": c="0001" elif a=="2": c="0010" elif a=="3": c="0011" elif a=="4": c="0100" elif a=="5": c="0101" elif a=="6": c="0110" elif a=="7": c="0111" elif a=="8": c="1000" elif a=="9": c="1001" elif a=="A": c="1010" elif a=="B": c="1011" elif a=="C": c="1100" elif a=="D": c="1101" elif a=="E": c="1110" elif a=="F": c="1111" else: c="invalid" return c a=len(no) b=0 l="" while b&lt;a: l=l+convert(no[b]) b+=1 print l </code></pre>
-10
2012-03-13T15:21:11Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
25,016,156
<pre><code>&gt;&gt;&gt; bin( 0xABC123EFFF ) </code></pre> <p>'0b1010101111000001001000111110111111111111'</p>
13
2014-07-29T13:10:58Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
28,407,262
<pre><code>a = raw_input('hex number\n') length = len(a) ab = bin(int(a, 16))[2:] while len(ab)&lt;(length * 4): ab = '0' + ab print ab </code></pre>
-1
2015-02-09T10:09:57Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
28,913,296
<p>I added the calculation for the number of bits to fill to Onedinkenedi's solution. Here is the resulting function:</p> <pre><code>def hextobin(h): return bin(int(h, 16))[2:].zfill(len(h) * 4) </code></pre> <p>Where 16 is the base you're converting from (hexadecimal), and 4 is how many bits you need to represent each digit, or log base 2 of the scale.</p>
0
2015-03-07T09:21:39Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
32,916,352
<pre><code>import binascii hexa_input = input('Enter hex String to convert to Binary: ') pad_bits=len(hexa_input)*4 Integer_output=int(hexa_input,16) Binary_output= bin(Integer_output)[2:]. zfill(pad_bits) print(Binary_output) """zfill(x) i.e. x no of 0 s to be padded left - Integers will overwrite 0 s starting from right side but remaining 0 s will display till quantity x [y:] where y is no of output chars which need to destroy starting from left""" </code></pre>
-1
2015-10-02T21:48:08Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
34,574,391
<pre><code> def conversion(): e=raw_input("enter hexadecimal no.:") e1=("a","b","c","d","e","f") e2=(10,11,12,13,14,15) e3=1 e4=len(e) e5=() while e3&lt;=e4: e5=e5+(e[e3-1],) e3=e3+1 print e5 e6=1 e8=() while e6&lt;=e4: e7=e5[e6-1] if e7=="A": e7=10 if e7=="B": e7=11 if e7=="C": e7=12 if e7=="D": e7=13 if e7=="E": e7=14 if e7=="F": e7=15 else: e7=int(e7) e8=e8+(e7,) e6=e6+1 print e8 e9=1 e10=len(e8) e11=() while e9&lt;=e10: e12=e8[e9-1] a1=e12 a2=() a3=1 while a3&lt;=1: a4=a1%2 a2=a2+(a4,) a1=a1/2 if a1&lt;2: if a1==1: a2=a2+(1,) if a1==0: a2=a2+(0,) a3=a3+1 a5=len(a2) a6=1 a7="" a56=a5 while a6&lt;=a5: a7=a7+str(a2[a56-1]) a6=a6+1 a56=a56-1 if a5&lt;=3: if a5==1: a8="000" a7=a8+a7 if a5==2: a8="00" a7=a8+a7 if a5==3: a8="0" a7=a8+a7 else: a7=a7 print a7, e9=e9+1 </code></pre>
-1
2016-01-03T07:42:54Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
36,884,411
<p>i have a short snipped hope that helps :-)</p> <pre><code>input = 'ABC123EFFF' for index, value in enumerate(input): print(value) print(bin(int(value,16)+16)[3:]) string = ''.join([bin(int(x,16)+16)[3:] for y,x in enumerate(input)]) print(string) </code></pre> <p>first i use your input and enumerate it to get each symbol. then i convert it to binary and trim from 3th position to the end. The trick to get the 0 is to add the max value of the input -> in this case always 16 :-) </p> <p>the short form ist the join method. Enjoy.</p>
0
2016-04-27T08:31:51Z
[ "python", "string", "binary", "hex", "string-formatting" ]
Convert hex to binary
1,425,493
<p>I have ABC123EFFF.</p> <p>I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).</p> <p>How?</p>
49
2009-09-15T06:41:37Z
37,221,884
<blockquote> <h1>Convert hex to binary, 42 digits and leading zeros?</h1> </blockquote> <p>We have several direct ways to accomplish this goal, without hacks using slices.</p> <p>First, before we can do any binary manipulation at all, convert to int (I presume this is in a string format, not as a literal):</p> <pre><code>&gt;&gt;&gt; integer = int('ABC123EFFF', 16) </code></pre> <h2>Most direct answer: Use the builtin function, <code>format</code></h2> <p>Then pass to <code>format</code>:</p> <pre><code>&gt;&gt;&gt; format(integer, '0&gt;42b') '001010101111000001001000111110111111111111' </code></pre> <p>This uses the formatting specification's <a href="https://docs.python.org/2/library/string.html#format-specification-mini-language" rel="nofollow">mini-language</a>. To break that down, here's the grammar form of it:</p> <pre><code>[[fill]align][sign][#][0][width][,][.precision][type] </code></pre> <p>To make that into a specification for our needs:</p> <pre><code>&gt;&gt;&gt; spec = '{fill}{align}{width}{type}'.format(fill='0', align='&gt;', width=42, type='b') &gt;&gt;&gt; format(integer, spec) '001010101111000001001000111110111111111111' </code></pre> <h2>String Formatting (Templating)</h2> <p>We can use that in a string using <code>str.format</code> method:</p> <pre><code>&gt;&gt;&gt; 'here is the binary form: {0:{spec}}'.format(integer, spec=spec) 'here is the binary form: 001010101111000001001000111110111111111111' </code></pre> <p>Or just put the spec directly in the original string:</p> <pre><code>&gt;&gt;&gt; 'here is the binary form: {0:0&gt;42b}'.format(integer) 'here is the binary form: 001010101111000001001000111110111111111111' </code></pre>
2
2016-05-14T02:34:52Z
[ "python", "string", "binary", "hex", "string-formatting" ]
How do you mix old-style and new-style Python classes?
1,425,714
<p>I've seen a few questions on this topic, but I haven't been able to find a definitive answer. </p> <p>I would like to know the proper way to use old-style classes in a new Python code base. Let's say for example that I have two fixed classes, <strong>A</strong> and <strong>B</strong>. If I want to subclass <strong>A</strong> and <strong>B</strong>, and convert to new-style classes (<strong>A2</strong> and <strong>B2</strong>), this works. However there is an issue if I want to create a new class <strong>C</strong>, from <strong>A2</strong> and <strong>B2</strong>. </p> <p>Therefore, is it possible to continue with this method, or do all classes have to conform to the old-style if any base class is defined as old-style?</p> <p>See the example code for clarification:</p> <pre><code>class A: def __init__(self): print 'class A' class B: def __init__(self): print 'class B' class A2(A,object): def __init__(self): super(A2, self).__init__() print 'class A2' class B2(B,object): def __init__(self): super(B2, self).__init__() print 'class B2' class C(A2, B2): def __init__(self): super(C,self).__init__() print 'class C' A2() print '---' B2() print '---' C() </code></pre> <p>The output of this code:</p> <pre><code>class A class A2 --- class B class B2 --- class A class A2 class C </code></pre> <p>As you can see, the problem is that in the call to <code>C()</code>, class <strong>B2</strong> was never initialized.</p> <p><hr /></p> <p><strong>Update - New-Style Class Example</strong></p> <p>I guess it is not clear what the correct initialization sequence should be when using <code>super</code>. Here is a working example where a call to super <strong>does</strong> initialize all base classes, not just <em>the first one it finds</em>.</p> <pre><code>class A(object): def __init__(self): super(A, self).__init__() print 'class A' class B(object): def __init__(self): super(B, self).__init__() print 'class B' class A2(A): def __init__(self): super(A2, self).__init__() print 'class A2' class B2(B): def __init__(self): super(B2, self).__init__() print 'class B2' class C(A2, B2): def __init__(self): super(C, self).__init__() print 'class C' C() </code></pre> <p>and produces the output:</p> <pre><code>class B class B2 class A class A2 class C </code></pre>
6
2009-09-15T07:41:44Z
1,425,998
<p>This is not a issue of mixing old and new style classes. super() does not call <em>all</em> base classes functions, it calls the first one it finds according the method resolution order. In this case A2, which in turn calls A.</p> <p>If you want to call both, do so explicitly:</p> <pre><code>class C(A2, B2): def __init__(self): A2.__init__(self) B2.__init__(self) print 'class C' </code></pre> <p>That should solve it.</p> <p>Update: </p> <p>The diamond inheritance problem as you refer to, is the question of which class to call in a diamond inheritance situation, like this:</p> <pre><code>class A: def method1(self): print 'class A' def method2(self): print 'class A' class B(A): def method1(self): print 'class B' class C(A): def method1(self): print 'class C' def method2(self): print 'class C' class D(B, C): pass </code></pre> <p>Now test this out:</p> <pre><code>&gt;&gt;&gt; D().method1() 'class B' </code></pre> <p>This is correct. It calls the first class' implementation. However, let's try this with method2:</p> <pre><code>&gt;&gt;&gt; D().method2() 'class A' </code></pre> <p>Oups, WRONG! It should have called class C.method2() here, because even though class B does not override method2, class C does. Now make class A a newstyle class:</p> <pre><code>class A(object): def method1(self): print 'class A' </code></pre> <p>And try again:</p> <pre><code>&gt;&gt;&gt; D().method1() 'class B' &gt;&gt;&gt; D().method2() 'class C' </code></pre> <p>and hey presto, it works. This is the method resolution order difference between new and old-style classes, and this is what sometimes makes it confusing to mix them.</p> <p>Notice how at no point both B and C gets called. This is true even if we call super.</p> <pre><code>class D(B, C): def method1(self): super(D, self).method1() def method2(self): super(D, self).method2() &gt;&gt;&gt; D().method1() 'class B' &gt;&gt;&gt; D().method2() 'class C' </code></pre> <p>If you want to call both B and C, you MUST call both explicitly.</p> <p>Now if you unbreak the diamond, like in your example having separate base classes, the result is different:</p> <pre><code>class A1(object): def method1(self): print 'class A1' def method2(self): print 'class A1' class A2(object): def method1(self): print 'class A2' def method2(self): print 'class A2' class B(A1): def method1(self): print 'class B' class C(A2): def method1(self): print 'class C' def method2(self): print 'class C' class D(B, C): def method1(self): super(D, self).method1() def method2(self): super(D, self).method2() &gt;&gt;&gt; D().method1() 'class B' &gt;&gt;&gt; D().method2() 'class A1' </code></pre> <p>This is also per design. Still nowhere two base classes gets called. If you want that to happen you still have to call both explicitly.</p>
6
2009-09-15T08:55:16Z
[ "python", "class", "multiple-inheritance", "instantiation" ]
reverse the string
1,425,721
<p>I have a content of strings and I have to reverse the order using python. the content is</p> <ol> <li>Python</li> <li>Java</li> <li>microsoft</li> </ol>
-1
2009-09-15T07:42:33Z
1,425,733
<p>If you want a new list:</p> <pre><code>a = ["Python", "Java", "Microsoft"] b = a[::-1] # b is now ["Microsoft", "Java", "Python"] </code></pre> <p>or</p> <pre><code>a = ["Python", "Java", "Microsoft"] b = list(reversed(a)) # b is now ["Microsoft", "Java", "Python"] </code></pre> <p>If you want to modify an existing list:</p> <pre><code>a = ["Python", "Java", "Microsoft"] a.reverse() # a is now ["Microsoft", "Java", "Python"] </code></pre> <p>If you want a list where each of the individual strings has had its characters reversed:</p> <pre><code>a = ["Python", "Java", "Microsoft"] b = [x[::-1] for x in a] # b is now ["nohtyP", "avaJ", "tfosorciM"] </code></pre> <p>The reason why using slice notation with <code>a[::-1]</code> returns a sequence that is the reverse of <code>a</code> is because slice notation works like this:</p> <pre><code>sequence[start:end:step] </code></pre> <p>since you specify <code>step</code> to be -1, that means that it works backwards through the sequence one by one, which is in effect the reverse of the sequence. (<code>start</code> and <code>end</code> being omitted uses their default values, i.e. the entire sequence.)</p>
25
2009-09-15T07:44:45Z
[ "python" ]
reverse the string
1,425,721
<p>I have a content of strings and I have to reverse the order using python. the content is</p> <ol> <li>Python</li> <li>Java</li> <li>microsoft</li> </ol>
-1
2009-09-15T07:42:33Z
1,425,740
<pre><code>&gt;&gt;&gt; l = ["Microsoft", "Java", "Python"] &gt;&gt;&gt; l.reverse() &gt;&gt;&gt; l ['Python', 'Java', 'Microsoft'] &gt;&gt;&gt; </code></pre>
1
2009-09-15T07:46:23Z
[ "python" ]
reverse the string
1,425,721
<p>I have a content of strings and I have to reverse the order using python. the content is</p> <ol> <li>Python</li> <li>Java</li> <li>microsoft</li> </ol>
-1
2009-09-15T07:42:33Z
1,425,744
<p>the most comprehensible option for sequences is to use "reversed", but the result is always a list, so for a string you could either use it and convert it to a string again by joining the elements, or use a slice with negative index (this later being more efficient, I guess):</p> <pre><code>s = "abcd" reversed(s) #-&gt; ['d','c','b','a'] "".join(_) #-&gt; 'dcba' #or s[::-1] #-&gt; 'dcba' </code></pre>
1
2009-09-15T07:48:33Z
[ "python" ]
reverse the string
1,425,721
<p>I have a content of strings and I have to reverse the order using python. the content is</p> <ol> <li>Python</li> <li>Java</li> <li>microsoft</li> </ol>
-1
2009-09-15T07:42:33Z
38,784,593
<pre><code>public class StringRev { public static void main(String[] args) { // text is containing dummy/ Test string String text="ReverseToString"; //StringBuilder sb=new StringBuilder(); // In this line I am creating the object of StringBuffer StringBuffer sb=new StringBuffer(); // using a for loop in decreasing order from length-1 to 0 for(int i=text.length()-1;i&gt;=0;i--){ // getting the character using index and appending in String buffer. sb.append(text.charAt(i)); } // converting StringBuffer value to String System.out.println(sb.toString()); } } //output will be "gnirtSoTesreveR" </code></pre>
-1
2016-08-05T08:25:40Z
[ "python" ]
Problem configparser in python
1,426,241
<p>Actually I am stuck in my work. I want to import a txt file into my python program which should have two lists of intergers.</p> <p>The following program is working fine but I need to import the list 'a' and 'b' with the help of configparser. </p> <p>It will be so nice if some one help me with it!</p> <p>I am a begineer in python so please try to answer in an easy way...!</p> <p>The program is as follow:</p> <pre><code>a=[5e6,6e6,7e6,8e6,8.5e6,9e6,9.5e6,10e6,11e6,12e6] p=[0.0,0.001,0.002,0.003,0.004,0.005,0.006,0.007,0.008,0.009,0.01,0.015,0.05,0.1,0.15,0.2] b=0 x=0 while b&lt;=10: c=a[b] x=0 print '\there is the outer loop\n',c while x&lt;=15: k=p[x] print'here is the inner loop\n',k x=x+1 b=b+1 </code></pre>
0
2009-09-15T09:57:38Z
1,426,255
<p>Seems like ConfigParser is not the best tool for the job. You may implement the parsing logic youself something like:</p> <pre><code>a, b = [], [] with open('myfile', 'r') as f: for num, line in enumerate(f.readlines()): if num &gt;= 10: b.push(line) else: a.push(line) </code></pre> <p>or you can make up some other logic to devide the lists in your file. It depends on the way you want to represent it in you file</p>
0
2009-09-15T10:01:27Z
[ "python", "configparser" ]
Problem configparser in python
1,426,241
<p>Actually I am stuck in my work. I want to import a txt file into my python program which should have two lists of intergers.</p> <p>The following program is working fine but I need to import the list 'a' and 'b' with the help of configparser. </p> <p>It will be so nice if some one help me with it!</p> <p>I am a begineer in python so please try to answer in an easy way...!</p> <p>The program is as follow:</p> <pre><code>a=[5e6,6e6,7e6,8e6,8.5e6,9e6,9.5e6,10e6,11e6,12e6] p=[0.0,0.001,0.002,0.003,0.004,0.005,0.006,0.007,0.008,0.009,0.01,0.015,0.05,0.1,0.15,0.2] b=0 x=0 while b&lt;=10: c=a[b] x=0 print '\there is the outer loop\n',c while x&lt;=15: k=p[x] print'here is the inner loop\n',k x=x+1 b=b+1 </code></pre>
0
2009-09-15T09:57:38Z
1,426,477
<p>The <a href="http://docs.python.org/library/json.html#module-json" rel="nofollow"><code>json</code> module</a> provides better support for lists in configuration files. Instead of the ConfigParser (no list support) format, try using <a href="http://json.org/" rel="nofollow"><code>JSON</code></a> for this purpose.</p> <blockquote> <p><code>JSON</code> (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make <code>JSON</code> an ideal data-interchange language.</p> </blockquote> <p>Since your question smells like homework, I'll suggest an ugly hack. Use <a href="http://docs.python.org/library/stdtypes.html#str.split" rel="nofollow"><code>str.split()</code></a> and <a href="http://docs.python.org/library/functions.html#float" rel="nofollow"><code>float()</code></a> to parse a list from a configuration file. Suppose the file <code>x.conf</code> contains:</p> <pre><code>[sect1] a=[5e6,6e6,7e6,8e6,8.5e6,9e6,9.5e6,10e6,11e6,12e6] </code></pre> <p>You can parse it with:</p> <pre><code>&gt;&gt;&gt; import ConfigParser &gt;&gt;&gt; cf=ConfigParser.ConfigParser() &gt;&gt;&gt; cf.read(['x.conf']) ['x.conf'] &gt;&gt;&gt; [float(s) for s in cf.get('sect1','a')[1:-1].split(',')] [5000000.0, 6000000.0, 7000000.0, 8000000.0, 8500000.0, 9000000.0, 9500000.0, 10000000.0, 11000000.0, 12000000.0] &gt;&gt;&gt; </code></pre> <p>(The brackets around the list could be dropped from the configuration file, making the <code>[1:-1]</code> hack unnecessary )</p>
0
2009-09-15T11:00:58Z
[ "python", "configparser" ]
Problem configparser in python
1,426,241
<p>Actually I am stuck in my work. I want to import a txt file into my python program which should have two lists of intergers.</p> <p>The following program is working fine but I need to import the list 'a' and 'b' with the help of configparser. </p> <p>It will be so nice if some one help me with it!</p> <p>I am a begineer in python so please try to answer in an easy way...!</p> <p>The program is as follow:</p> <pre><code>a=[5e6,6e6,7e6,8e6,8.5e6,9e6,9.5e6,10e6,11e6,12e6] p=[0.0,0.001,0.002,0.003,0.004,0.005,0.006,0.007,0.008,0.009,0.01,0.015,0.05,0.1,0.15,0.2] b=0 x=0 while b&lt;=10: c=a[b] x=0 print '\there is the outer loop\n',c while x&lt;=15: k=p[x] print'here is the inner loop\n',k x=x+1 b=b+1 </code></pre>
0
2009-09-15T09:57:38Z
1,426,520
<p>Yea, the config parser probably isn't the best choice...but if you really want to, try this:</p> <pre><code>import unittest from ConfigParser import SafeConfigParser from cStringIO import StringIO def _parse_float_list(string_value): return [float(v.strip()) for v in string_value.split(',')] def _generate_float_list(float_values): return ','.join(str(value) for value in float_values) def get_float_list(parser, section, option): string_value = parser.get(section, option) return _parse_float_list(string_value) def set_float_list(parser, section, option, float_values): string_value = _generate_float_list(float_values) parser.set(section, option, string_value) class TestConfigParser(unittest.TestCase): def setUp(self): self.a = [5e6,6e6,7e6,8e6,8.5e6,9e6,9.5e6,10e6,11e6,12e6] self.p = [0.0,0.001,0.002,0.003,0.004,0.005,0.006,0.007,0.008,0.009,0.01,0.015,0.05,0.1,0.15,0.2] def testRead(self): parser = SafeConfigParser() f = StringIO('''[values] a: 5e6, 6e6, 7e6, 8e6, 8.5e6, 9e6, 9.5e6, 10e6, 11e6, 12e6 p: 0.0 , 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009, 0.01 , 0.015, 0.05 , 0.1 , 0.15 , 0.2 ''') parser.readfp(f) self.assertEquals(self.a, get_float_list(parser, 'values', 'a')) self.assertEquals(self.p, get_float_list(parser, 'values', 'p')) def testRoundTrip(self): parser = SafeConfigParser() parser.add_section('values') set_float_list(parser, 'values', 'a', self.a) set_float_list(parser, 'values', 'p', self.p) self.assertEquals(self.a, get_float_list(parser, 'values', 'a')) self.assertEquals(self.p, get_float_list(parser, 'values', 'p')) if __name__ == '__main__': unittest.main() </code></pre>
0
2009-09-15T11:09:39Z
[ "python", "configparser" ]
Live UI update of model changes when the model contains plain data structures only
1,426,272
<p>Please consult me with your opinions on the following topic:</p> <p>I have a model - a structure of the objects. Such as:</p> <ul> <li><p>Event, containing participants</p></li> <li><p>Current task</p></li> <li><p>Assignee of each task</p></li> </ul> <p>The model is going to be pickled on the server and transferred over the network to the client GUI application. Because of the pickle I'd want to keep the model classes as simple as possible (i.e. just simple classes with data fields only, no any single method inside). As a result I can't create signals (such as OnUpdate) on the model objects.</p> <p>Sometimes the server will send model updates. Such as "Task text changed". When the update is applied, I need it to be reflected in the UI. In the case of task text change it shall be change of the label in the UI. I'd want only related controls to be changed, so the whole UI update is not the best solution.</p> <p>On the other hand, would not like to traverse the whole model in the search of changes - that would be too resource intensive.</p> <p>So, what is the best pattern of notifying the UI about changes on the plain data structures?</p>
2
2009-09-15T10:05:36Z
1,426,368
<p>You may be operating under a mis-conception: pickles don't include the code from classes that are pickled. You can add methods to your data structures, and it will not increase the size of your pickles.</p> <p>This is a common misunderstanding about pickles. They don't include code.</p>
0
2009-09-15T10:36:43Z
[ "python", "design-patterns", "architecture" ]
Live UI update of model changes when the model contains plain data structures only
1,426,272
<p>Please consult me with your opinions on the following topic:</p> <p>I have a model - a structure of the objects. Such as:</p> <ul> <li><p>Event, containing participants</p></li> <li><p>Current task</p></li> <li><p>Assignee of each task</p></li> </ul> <p>The model is going to be pickled on the server and transferred over the network to the client GUI application. Because of the pickle I'd want to keep the model classes as simple as possible (i.e. just simple classes with data fields only, no any single method inside). As a result I can't create signals (such as OnUpdate) on the model objects.</p> <p>Sometimes the server will send model updates. Such as "Task text changed". When the update is applied, I need it to be reflected in the UI. In the case of task text change it shall be change of the label in the UI. I'd want only related controls to be changed, so the whole UI update is not the best solution.</p> <p>On the other hand, would not like to traverse the whole model in the search of changes - that would be too resource intensive.</p> <p>So, what is the best pattern of notifying the UI about changes on the plain data structures?</p>
2
2009-09-15T10:05:36Z
2,977,996
<p>You may add a flag, e.g. self.isOnClientSide, and check it in every update handler, so that you can use different logic in either case.</p> <pre><code>def onUpdateFoo(self): if self.isOnClientSide: return self.onUpdateFooOnClient() else: return self.onUpdateFooOnServer() </code></pre> <p>Change this flag accordingly right after un-pickling.</p>
0
2010-06-04T21:41:56Z
[ "python", "design-patterns", "architecture" ]
What are the ways to run a server side script forever?
1,427,000
<p>I need to run a server side script like Python "forever" (or as long as possible without loosing state), so they can keep <a href="http://stackoverflow.com/questions/1424511/how-do-scripting-languages-use-sockets">sockets open</a> and asynchronously react to events like data received. For example if I use <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> for socket communication.</p> <ul> <li>How would I manage something like this? </li> <li>Am I confused? or are there are better ways to implement asynchronous socket communication?</li> <li>After starting the script once via Apache server, how do I stop it running?</li> </ul>
0
2009-09-15T12:51:00Z
1,427,076
<p>You can just write an script that is continuously in a while block waiting for the connection to happen and waits for a signal to close it.</p> <p><a href="http://docs.python.org/library/signal.html" rel="nofollow">http://docs.python.org/library/signal.html</a></p> <p>Then to stop it you just need to run another script that sends that signal to him.</p>
1
2009-09-15T13:08:09Z
[ "python", "apache", "sockets", "webserver", "twisted" ]
What are the ways to run a server side script forever?
1,427,000
<p>I need to run a server side script like Python "forever" (or as long as possible without loosing state), so they can keep <a href="http://stackoverflow.com/questions/1424511/how-do-scripting-languages-use-sockets">sockets open</a> and asynchronously react to events like data received. For example if I use <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> for socket communication.</p> <ul> <li>How would I manage something like this? </li> <li>Am I confused? or are there are better ways to implement asynchronous socket communication?</li> <li>After starting the script once via Apache server, how do I stop it running?</li> </ul>
0
2009-09-15T12:51:00Z
1,427,086
<p>I think <a href="http://en.wikipedia.org/wiki/Comet%5F%28programming%29" rel="nofollow">Comet</a> is what you're looking for. Make sure to take a look at Tornado too.</p>
0
2009-09-15T13:09:04Z
[ "python", "apache", "sockets", "webserver", "twisted" ]
What are the ways to run a server side script forever?
1,427,000
<p>I need to run a server side script like Python "forever" (or as long as possible without loosing state), so they can keep <a href="http://stackoverflow.com/questions/1424511/how-do-scripting-languages-use-sockets">sockets open</a> and asynchronously react to events like data received. For example if I use <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> for socket communication.</p> <ul> <li>How would I manage something like this? </li> <li>Am I confused? or are there are better ways to implement asynchronous socket communication?</li> <li>After starting the script once via Apache server, how do I stop it running?</li> </ul>
0
2009-09-15T12:51:00Z
1,427,125
<p>You can use a ‘double fork’ to run your code in a new background process unbound to the old one. See eg <a href="http://code.activestate.com/recipes/278731/" rel="nofollow">this</a> recipe with more explanatory comments than you could possibly want.</p> <p>I wouldn't recommend this as a primary way of running background tasks for a web site. If your Python is embedded in an Apache process, for example, you'll be forking more than you want. Better to invoke the daemon separately (just under a similar low-privilege user).</p> <blockquote> <p>After starting the script once via Apache server, how do I stop it running?</p> </blockquote> <p>You have your second fork write the process number (pid) of the daemon process to a file, and then read the pid from that file and send it a terminate signal (<code>os.kill(pid, signal.SIG_TERM)</code>).</p> <blockquote> <p>Am I confused?</p> </blockquote> <p>That's the question! I'm assuming you are trying to have a background process that responds on a different port to the web interface for some sort of unusual net service. If you merely talking about responding to normal web requests you shoudn't be doing this, you should rely on Apache to handle your sockets and service one request at a time.</p>
1
2009-09-15T13:17:21Z
[ "python", "apache", "sockets", "webserver", "twisted" ]
What are the ways to run a server side script forever?
1,427,000
<p>I need to run a server side script like Python "forever" (or as long as possible without loosing state), so they can keep <a href="http://stackoverflow.com/questions/1424511/how-do-scripting-languages-use-sockets">sockets open</a> and asynchronously react to events like data received. For example if I use <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> for socket communication.</p> <ul> <li>How would I manage something like this? </li> <li>Am I confused? or are there are better ways to implement asynchronous socket communication?</li> <li>After starting the script once via Apache server, how do I stop it running?</li> </ul>
0
2009-09-15T12:51:00Z
1,429,758
<p>You may want to look at FastCGI, it sounds exactly like what you are looking for, but I'm not sure if it's under current development. It uses a CGI daemon and a special apache module to communicate with it. Since the daemon is long running, you don't have the fork/exec cost. But as a cost of managing your own resources (no automagic cleanup on every request)</p> <p>One reason why this style of FastCGI isn't used much anymore is there are ways to embed interpreters into the Apache binary and have them run in server. I'm not familiar with mod_python, but i know mod_perl has configuration to allow long running processes. Be careful here, since a long running process in the server can cause resource leaks.</p> <p>A general question is: what do you want to do? Why do you need this second process, but yet somehow controlled by apache? Why can'ty ou just build a daemon that talks to apache, why does it have to be controlled by apache?</p>
0
2009-09-15T21:38:08Z
[ "python", "apache", "sockets", "webserver", "twisted" ]
What are the ways to run a server side script forever?
1,427,000
<p>I need to run a server side script like Python "forever" (or as long as possible without loosing state), so they can keep <a href="http://stackoverflow.com/questions/1424511/how-do-scripting-languages-use-sockets">sockets open</a> and asynchronously react to events like data received. For example if I use <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> for socket communication.</p> <ul> <li>How would I manage something like this? </li> <li>Am I confused? or are there are better ways to implement asynchronous socket communication?</li> <li>After starting the script once via Apache server, how do I stop it running?</li> </ul>
0
2009-09-15T12:51:00Z
1,431,519
<p>If you are using twisted then it has a whole infrastructure for starting and stopping daemons.</p> <p><a href="http://twistedmatrix.com/projects/core/documentation/howto/application.html" rel="nofollow">http://twistedmatrix.com/projects/core/documentation/howto/application.html</a></p> <blockquote> <p>How would I manage something like this?</p> </blockquote> <p>Twisted works well for this, read the link above</p> <blockquote> <p>Am I confused? or are there are better ways to implement asynchronous socket communication?</p> </blockquote> <p>Twisted is very good at asynchronous socket communications. It is hard on the brain until you get the hang of it though!</p> <blockquote> <p>After starting the script once via Apache server, how do I stop it running?</p> </blockquote> <p>The twisted tools assume command line access, so you'd have to write a cgi wrapper for starting / stopping them if I understand what you want to do.</p>
3
2009-09-16T07:36:21Z
[ "python", "apache", "sockets", "webserver", "twisted" ]
Calling Py_Finalize() from C
1,427,002
<p>This is a follow up to <a href="http://stackoverflow.com/questions/1417473/call-python-from-c">http://stackoverflow.com/questions/1417473/call-python-from-c</a></p> <p>At the startup of the programm I call the following function to initialize the interpreter:</p> <pre><code>void initPython(){ PyEval_InitThreads(); Py_Initialize(); PyEval_ReleaseLock(); } </code></pre> <p>Every thread creates it's own data structure and acquires the lock with:</p> <pre><code>PyGILState_STATE gstate; gstate = PyGILState_Ensure(); //call python API, process results PyGILState_Release(gstate); </code></pre> <p>Rather straight forward once you understood the GIL, but the problem is that I get a segfault when calling Py_Finalize().</p> <pre><code>void exitPython(){ PyEval_AcquireLock(); Py_Finalize(); } </code></pre> <p>The reference is rather dubious about Py_Finalize() (or maybe I'm just reading it the wrong way) and I'm not sure if PyEval_AcquireLock() can acquire the lock if there are some active threads and what happens if there are active threads when Py_Finalize() is called. </p> <p>Anyways, I get a segfault even if I'm sure that all threads have finished their work, but only if at least one was created. E.g. calling initPython() followed from exitPython() creates no error.</p> <p>I could just ignore the problem and hope the OS knows what it does, but I'd prefere if I could figure out what is going on..</p>
9
2009-09-15T12:51:46Z
1,432,160
<p>Have you tried commenting out all the 'work' done in your threads? Replace it with a busy loop or a sleep or something. That will help pinpoint whether it is your initialisation/shutdown code, or something you're actually doing to Python in between. Perhaps you're not setting up the threads properly - there are a lot of thread-specific functions in the C API and I'm not sure which ones you need to ensure proper operation.</p>
1
2009-09-16T10:25:06Z
[ "c++", "python", "c" ]
Calling Py_Finalize() from C
1,427,002
<p>This is a follow up to <a href="http://stackoverflow.com/questions/1417473/call-python-from-c">http://stackoverflow.com/questions/1417473/call-python-from-c</a></p> <p>At the startup of the programm I call the following function to initialize the interpreter:</p> <pre><code>void initPython(){ PyEval_InitThreads(); Py_Initialize(); PyEval_ReleaseLock(); } </code></pre> <p>Every thread creates it's own data structure and acquires the lock with:</p> <pre><code>PyGILState_STATE gstate; gstate = PyGILState_Ensure(); //call python API, process results PyGILState_Release(gstate); </code></pre> <p>Rather straight forward once you understood the GIL, but the problem is that I get a segfault when calling Py_Finalize().</p> <pre><code>void exitPython(){ PyEval_AcquireLock(); Py_Finalize(); } </code></pre> <p>The reference is rather dubious about Py_Finalize() (or maybe I'm just reading it the wrong way) and I'm not sure if PyEval_AcquireLock() can acquire the lock if there are some active threads and what happens if there are active threads when Py_Finalize() is called. </p> <p>Anyways, I get a segfault even if I'm sure that all threads have finished their work, but only if at least one was created. E.g. calling initPython() followed from exitPython() creates no error.</p> <p>I could just ignore the problem and hope the OS knows what it does, but I'd prefere if I could figure out what is going on..</p>
9
2009-09-15T12:51:46Z
1,434,508
<p>Yeah the whole section is rather dubious but I think I've got my mistake.</p> <p>I've got to save the PyThreadState when initializing the interpreter and swap this state back in when I finish it (no idea why I need a specific ThreadState to call Finalize - shouldn't every State work as well?)</p> <p>Anyways the example if other people got the same problem:</p> <pre><code>PyThreadState *mainstate; void initPython(){ PyEval_InitThreads(); Py_Initialize(); mainstate = PyThreadState_Swap(NULL); PyEval_ReleaseLock(); } void exitPython(){ PyEval_AcquireLock(); PyThreadState_Swap(mainstate); Py_Finalize(); } </code></pre> <p>The only problem with this is, that I can acquire the lock like every other thread, even if there are still threads working. The API doesn't mention what happens when Finalize() is called while other threads are still working. Sounds like the perfect example of a race condition..</p>
7
2009-09-16T17:48:38Z
[ "c++", "python", "c" ]
Calling Py_Finalize() from C
1,427,002
<p>This is a follow up to <a href="http://stackoverflow.com/questions/1417473/call-python-from-c">http://stackoverflow.com/questions/1417473/call-python-from-c</a></p> <p>At the startup of the programm I call the following function to initialize the interpreter:</p> <pre><code>void initPython(){ PyEval_InitThreads(); Py_Initialize(); PyEval_ReleaseLock(); } </code></pre> <p>Every thread creates it's own data structure and acquires the lock with:</p> <pre><code>PyGILState_STATE gstate; gstate = PyGILState_Ensure(); //call python API, process results PyGILState_Release(gstate); </code></pre> <p>Rather straight forward once you understood the GIL, but the problem is that I get a segfault when calling Py_Finalize().</p> <pre><code>void exitPython(){ PyEval_AcquireLock(); Py_Finalize(); } </code></pre> <p>The reference is rather dubious about Py_Finalize() (or maybe I'm just reading it the wrong way) and I'm not sure if PyEval_AcquireLock() can acquire the lock if there are some active threads and what happens if there are active threads when Py_Finalize() is called. </p> <p>Anyways, I get a segfault even if I'm sure that all threads have finished their work, but only if at least one was created. E.g. calling initPython() followed from exitPython() creates no error.</p> <p>I could just ignore the problem and hope the OS knows what it does, but I'd prefere if I could figure out what is going on..</p>
9
2009-09-15T12:51:46Z
28,080,794
<p>I am also getting similar problem while running scripts containing <code>pyxhook</code> from different threads through embedded interpreter. </p> <p>There is no problem if one script running at a time. The hook is released properly but if two or more script ran in parallel the hooking is not stopped. Though my scripts returned properly and <code>cancel()</code> from <code>pyxhook</code> also returned properly, I think still some threads are running related to <code>xlib</code>. This <code>pyxhook</code> problem I have solved by keeping a global flag to watch if <code>pyxhook</code> is already running and not re-initializing <code>pyxhook</code> from every thread.</p> <p>Now regarding <code>Py_Finalize()</code>, if <code>pyxhook</code> is re-initialized in every thread:</p> <p>if I do not call <code>PyEval_AcquireLock()</code> and <code>PyThreadState_Swap()</code> before calling <code>Py_Finalize()</code> it terminates in Linux but not in Win32. In Win32 there is a problem if I do not go through <code>PyEval_AcquireLock()</code> and <code>PyThreadState_Swap()</code>.</p> <p>For the time being the temporary solution for me is to terminate differently in two different OS. </p>
0
2015-01-22T03:27:15Z
[ "c++", "python", "c" ]
Project Euler # 255
1,427,040
<p><a href="http://projecteuler.net/index.php?section=problems&amp;id=255" rel="nofollow">Project euler problem #255</a> is quite mathematical. I figured out how it is done for given example. Since I am a newbie in Python, I am not sure how to handle long range values. Below is the solution I have. But how does it work for 10^13 and 10^14?</p> <pre><code>def ceil(a, b): return (a + b - 1) / b; def func(a, b): return (b + ceil(a, b)) / 2; def calculate(a): ctr = 1; y = 200; while 1: z = func(a, y); if z == y: return ctr; y = z; ctr += 1; result = sum(map(calculate, xrange(10000, 100000))) / 9e4; print "%.10f" % result; </code></pre> <p>This gives 3.2102888889.</p>
4
2009-09-15T13:01:56Z
1,427,212
<p>Don't use <code>map</code>. It generates a big list in memory.</p> <p>Don't use <code>xrange</code>. It is limited to short integers.</p> <p>Use generators instead.</p> <pre><code># No changes on `ceil()`, `func()` and `calculate()` def generate_sequence(start, stop): while start &lt; stop: yield start start += 1 result = sum(calculate(n) for n in generate_sequence(10**13, 10**14)) print "%.10f" % result; </code></pre> <p>That will run. But it will take a long time to sum <code>10**14 - 10**13 = 90,000,000,000,000</code> results. Maybe there's something else you can do to optimize <em>(hint, hint)</em></p>
4
2009-09-15T13:34:59Z
[ "python" ]
Project Euler # 255
1,427,040
<p><a href="http://projecteuler.net/index.php?section=problems&amp;id=255" rel="nofollow">Project euler problem #255</a> is quite mathematical. I figured out how it is done for given example. Since I am a newbie in Python, I am not sure how to handle long range values. Below is the solution I have. But how does it work for 10^13 and 10^14?</p> <pre><code>def ceil(a, b): return (a + b - 1) / b; def func(a, b): return (b + ceil(a, b)) / 2; def calculate(a): ctr = 1; y = 200; while 1: z = func(a, y); if z == y: return ctr; y = z; ctr += 1; result = sum(map(calculate, xrange(10000, 100000))) / 9e4; print "%.10f" % result; </code></pre> <p>This gives 3.2102888889.</p>
4
2009-09-15T13:01:56Z
1,428,255
<p>90,000,000,000,000 is a lot of numbers to check, I tried checking every millionth number and thought the average would be close enough, but to no avail.</p>
0
2009-09-15T16:35:40Z
[ "python" ]
Project Euler # 255
1,427,040
<p><a href="http://projecteuler.net/index.php?section=problems&amp;id=255" rel="nofollow">Project euler problem #255</a> is quite mathematical. I figured out how it is done for given example. Since I am a newbie in Python, I am not sure how to handle long range values. Below is the solution I have. But how does it work for 10^13 and 10^14?</p> <pre><code>def ceil(a, b): return (a + b - 1) / b; def func(a, b): return (b + ceil(a, b)) / 2; def calculate(a): ctr = 1; y = 200; while 1: z = func(a, y); if z == y: return ctr; y = z; ctr += 1; result = sum(map(calculate, xrange(10000, 100000))) / 9e4; print "%.10f" % result; </code></pre> <p>This gives 3.2102888889.</p>
4
2009-09-15T13:01:56Z
1,546,544
<p>Even a very fast calculation for each number will take too long. To satisfy the 1 minute rule you'd need to solve/add 1.5 Trillion numbers per second.</p> <p>I think there must be a way to compute the result more directly.</p>
1
2009-10-09T23:35:21Z
[ "python" ]
Project Euler # 255
1,427,040
<p><a href="http://projecteuler.net/index.php?section=problems&amp;id=255" rel="nofollow">Project euler problem #255</a> is quite mathematical. I figured out how it is done for given example. Since I am a newbie in Python, I am not sure how to handle long range values. Below is the solution I have. But how does it work for 10^13 and 10^14?</p> <pre><code>def ceil(a, b): return (a + b - 1) / b; def func(a, b): return (b + ceil(a, b)) / 2; def calculate(a): ctr = 1; y = 200; while 1: z = func(a, y); if z == y: return ctr; y = z; ctr += 1; result = sum(map(calculate, xrange(10000, 100000))) / 9e4; print "%.10f" % result; </code></pre> <p>This gives 3.2102888889.</p>
4
2009-09-15T13:01:56Z
1,549,435
<p><a href="http://python.org/doc/2.5.2/lib/typesseq-xrange.html" rel="nofollow">3.6.3 XRange Type</a> :</p> <blockquote> <p>"3.6.3 XRange Type</p> <p>The xrange type is an immutable sequence which is commonly used for looping. The advantage of the xrange type is that an xrange object will always take the same amount of memory, no matter the size of the range it represents. There are no consistent performance advantages.</p> <p>XRange objects have very little behavior: they only support indexing, iteration, and the len() function."</p> </blockquote> <p>maybe ... optimize your floor and ceiling functions? :P</p>
0
2009-10-11T00:07:56Z
[ "python" ]
Managing object instances
1,427,479
<p>I want to be able to create and unknown number of objects. I'm not sure if there is a better way to manage and reference them.</p> <p>Lets use a standard OOP example... say every time a user enters a name for a pet in a text field and clicks a button a new pet object is created via the petFactory function.</p> <pre><code>function pet(name) { this.name= name; } function petFactory(textFieldInput) { var x = new pet(textFieldInput) } </code></pre> <p>Since there's no way, that I know of (besides an eval function), to dynamically use a new, unique variable name for the pet every time petFactory is called, x is reassigned to a new object and the last pet is lost. What I've been doing is pushing the pet object onto an array as soon as it's initialized.</p> <pre><code>petArray.push(this); </code></pre> <p>So if I wanted the pet named 'mrFuzzyButtoms' I could loop through an indexed array until I found the object with the instance variable 'mrFuzzyButtoms'</p> <pre><code>for (n in petArray) { if (petarray[n].name == 'mrFuzzyBottoms') { // Kill mrFuzzyBottoms } } </code></pre> <p>or I could use an associative array...whatever...but the array is the only method I know for doing this. Besides using an eval function to create unique variable names from strings but some languages don't have an eval function (actionscript3) and then there is the security risk. </p> <p>Is there a better way to do this?</p> <p><strong>Edit</strong>: Right now I'm working in Python, JavaScript and ActionScript.</p>
1
2009-09-15T14:18:36Z
1,427,506
<p><strong>"I could use an associative array"</strong> Correct.</p> <p><strong>"the array is the only method I know for doing this."</strong></p> <p>Learn about "Mappings" or "Dictionaries" as soon as you can. You will find that it does exactly what you're asking for.</p> <p>What language are you using? If you provide a specific language, we can provide specific links to the "Map" structure in that language.</p>
3
2009-09-15T14:22:52Z
[ "javascript", "python", "actionscript-3", "oop" ]
Managing object instances
1,427,479
<p>I want to be able to create and unknown number of objects. I'm not sure if there is a better way to manage and reference them.</p> <p>Lets use a standard OOP example... say every time a user enters a name for a pet in a text field and clicks a button a new pet object is created via the petFactory function.</p> <pre><code>function pet(name) { this.name= name; } function petFactory(textFieldInput) { var x = new pet(textFieldInput) } </code></pre> <p>Since there's no way, that I know of (besides an eval function), to dynamically use a new, unique variable name for the pet every time petFactory is called, x is reassigned to a new object and the last pet is lost. What I've been doing is pushing the pet object onto an array as soon as it's initialized.</p> <pre><code>petArray.push(this); </code></pre> <p>So if I wanted the pet named 'mrFuzzyButtoms' I could loop through an indexed array until I found the object with the instance variable 'mrFuzzyButtoms'</p> <pre><code>for (n in petArray) { if (petarray[n].name == 'mrFuzzyBottoms') { // Kill mrFuzzyBottoms } } </code></pre> <p>or I could use an associative array...whatever...but the array is the only method I know for doing this. Besides using an eval function to create unique variable names from strings but some languages don't have an eval function (actionscript3) and then there is the security risk. </p> <p>Is there a better way to do this?</p> <p><strong>Edit</strong>: Right now I'm working in Python, JavaScript and ActionScript.</p>
1
2009-09-15T14:18:36Z
1,427,512
<p>This what collection classes (lists, dictionaries/maps, sets) are for; to collect a number of instances. For the above case I would probably use a map (class name varies depending on language) from name to object. </p>
2
2009-09-15T14:23:56Z
[ "javascript", "python", "actionscript-3", "oop" ]
Managing object instances
1,427,479
<p>I want to be able to create and unknown number of objects. I'm not sure if there is a better way to manage and reference them.</p> <p>Lets use a standard OOP example... say every time a user enters a name for a pet in a text field and clicks a button a new pet object is created via the petFactory function.</p> <pre><code>function pet(name) { this.name= name; } function petFactory(textFieldInput) { var x = new pet(textFieldInput) } </code></pre> <p>Since there's no way, that I know of (besides an eval function), to dynamically use a new, unique variable name for the pet every time petFactory is called, x is reassigned to a new object and the last pet is lost. What I've been doing is pushing the pet object onto an array as soon as it's initialized.</p> <pre><code>petArray.push(this); </code></pre> <p>So if I wanted the pet named 'mrFuzzyButtoms' I could loop through an indexed array until I found the object with the instance variable 'mrFuzzyButtoms'</p> <pre><code>for (n in petArray) { if (petarray[n].name == 'mrFuzzyBottoms') { // Kill mrFuzzyBottoms } } </code></pre> <p>or I could use an associative array...whatever...but the array is the only method I know for doing this. Besides using an eval function to create unique variable names from strings but some languages don't have an eval function (actionscript3) and then there is the security risk. </p> <p>Is there a better way to do this?</p> <p><strong>Edit</strong>: Right now I'm working in Python, JavaScript and ActionScript.</p>
1
2009-09-15T14:18:36Z
1,429,344
<pre><code>#!/usr/bin/env python """Playing with pets. """ class Pet(object): """A pet with a name.""" def __init__(self, name): """Create a pet with a `name`. """ self._name = name @property def name(self): # name is read-only return self._name def __repr__(self): """ &gt;&gt;&gt; eval(repr(self)) == self """ klass = self.__class__.__name__ return "%s('%s')" % (klass, self.name.replace("'", r"\'")) def __eq__(self, other): return repr(self) == repr(other) name2pet = {} # combined register of all pets @classmethod def get(cls, name): """Return a pet with `name`. Try to get the pet registered by `name` otherwise register a new pet and return it """ register = cls.name2pet try: return register[name] except KeyError: pet = register[name] = cls(name) # no duplicates allowed Pet.name2pet.setdefault(name, []).append(pet) return pet class Cat(Pet): name2pet = {} # each class has its own registry class Dog(Pet): name2pet = {} def test(): assert eval(repr(Cat("Teal'c"))) == Cat("Teal'c") pets = [Pet('a'), Cat('a'), Dog('a'), Cat.get('a'), Dog.get('a')] assert all(pet.name == 'a' for pet in pets) cat, dog = Cat.get('pet'), Dog.get('pet') assert repr(cat) == "Cat('pet')" and repr(dog) == "Dog('pet')" assert dog is not cat assert dog != cat assert cat.name == dog.name assert all(v == [Cat(k), Dog(k)] for k, v in Pet.name2pet.items()), Pet.name2pet try: cat.name = "cat" # .name is read-only except AttributeError: pass try: assert 0 except AssertionError: return "OK" raise AssertionError("Assertions must be enabled during the test") if __name__=="__main__": print test() </code></pre> <p><a href="http://gist.github.com/187588" rel="nofollow">pet.py</a></p>
0
2009-09-15T20:06:13Z
[ "javascript", "python", "actionscript-3", "oop" ]
Problem with import in Python
1,427,855
<p>[Closing NOTE] Thank you everyone that trying to help me.</p> <p>I've found the problem and it have nothing to do with python understanding of mine (which is little). :p</p> <p>The problem is that I edit the wrong branch of the same project, Main.py in one branch and XWinInfos.py in another branch.</p> <p>Thanks anyway.</p> <p>[Original Question] I am a Java/PHP/Delphi programmer and only use Python when hack someone else program -- never to write a complex Python myself. Since I have a short free time this week, I determine to write something non-trivia with Python and here is my problem</p> <p>First I have python files like this:</p> <pre><code>src/ main.py SomeUtils.py </code></pre> <p>In "SomeUtils.py, I have a few functions and one class:</p> <pre><code>... def funct1 ... def funct2 ... class MyClass1: __init__(self): self. .... ... </code></pre> <p>Then in "main.py", I use the function and class:</p> <pre><code>from SomeUtils import *; def main(): funct1(); # Use funct1 without problem; aMyObj1 = MyClass1(); # Use MyClass1 with error if (__name__ == "__main__"): main(); </code></pre> <p>The problem is that the functions are used without any problem what so ever but I cannot use the class.</p> <p>The error is:</p> <pre><code>NameError: global name 'MyClass1' is not defined </code></pre> <p>What is the problem here? and What can I do?</p> <p>EDIT: Thanks for answers for I still have problem. :( When I change the import statements to:</p> <pre><code>from SomeUtils import funct1 from SomeUtils import MyClass1 </code></pre> <p>I have this error </p> <pre><code>ImportError: cannot import name MyClass1</code></pre> <p><b>EDIT 2:----------------------------------------------------------</b></p> <p>Thanks you guys.</p> <p>I think, it may be better to post the actual code, so here it is:</p> <p>NOTE: I am aware about ";" and "(...)" but I like it this way.</p> <p>Here is the dir structure. <img src="http://dl.getdropbox.com/u/1961549/images/Python%5Fimport%5Fprolem%5Fdir%5F.png" alt="DIRS" /> as you see, I just add an empty <strong>init</strong>.py but it seems to make no different.</p> <p>Here is main.py:</p> <pre><code> from XWinInfos import GetCurrentWindowTitle; from XWinInfos import XWinInfo; def main(): print GetCurrentWindowTitle(); aXWinInfo = XWinInfo(); if (__name__ == "__main__"): main(); </code></pre> <p>Here is XWinInfos.py:</p> <pre><code>from subprocess import Popen; from subprocess import PIPE; from RegExUtils import GetTail_ofLine_withPrefix; def GetCurrentWindowID(): aXProp = Popen(["xprop", "-root"], stdout=PIPE).communicate()[0]; aLine = GetTail_ofLine_withPrefix("_NET_ACTIVE_WINDOW\(WINDOW\): window id # 0x", aXProp); return aLine; def GetCurrentWindowTitle(): aWinID = GetCurrentWindowID(); aWinTitle = GetWindowTitle(aWinID); return aWinTitle; def GetWindowTitle(pWinID): if (aWinID == None): return None aWMCtrlList = Popen(["wmctrl", "-l"], stdout=PIPE).communicate()[0]; aWinTitle = GetTail_ofLine_withPrefix("0x[0-9a-fA-F]*" + aWinID + "[ ]+[\-]?[0-9]+[ ]+[^\ ]+[ ]+", aWMCtrlList); return aWinTitle; class XWinInfo: def __init__(self): aWinID = GetCurrentWindowID(); self.WinID = pWinID; self.Title = GetWindowTitle(pWinID); </code></pre> <p>The file RegExUtils.py holds a function "GetTail_ofLine_withPrefix" which work fine so.</p> <p>If I use "from XWinInfos import *;", the error goes "NameError: global name 'XWinInfo' is not defined".</p> <p>If I use "from XWinInfos import XWinInfo;", the error goes "ImportError: cannot import name XWinInfo".</p> <p>Please helps. Thanks in advance.</p>
0
2009-09-15T15:24:20Z
1,427,881
<p>why are you importing from <code>XWinInfos</code>? you should be importing from <code>SomeUtils</code>. Not to mention that <code>*</code>-style imports are discouraged.</p> <p><strong>Edit</strong>: your error</p> <blockquote> <p>ImportError: cannot import name MyClass1</p> </blockquote> <p>basically tells you that there is no <code>MyClass1</code> defined in the <code>SomeUtils</code>. It could be because you have another <code>SomeUtils.py</code> file somewhere on the system path and it being imported instead. If that file doesn't have <code>MyClass1</code>, you'd get this error.</p> <p><strong>Again:</strong> it's irrelevant whether you class <code>MyClass1</code> exist. What might be the case is that you have another <code>XWinInfos.p(y|o|w)</code> somewhere on your system and it's being imported. Otherwise: <strong>norepro</strong>.</p>
2
2009-09-15T15:28:46Z
[ "python", "import" ]
Problem with import in Python
1,427,855
<p>[Closing NOTE] Thank you everyone that trying to help me.</p> <p>I've found the problem and it have nothing to do with python understanding of mine (which is little). :p</p> <p>The problem is that I edit the wrong branch of the same project, Main.py in one branch and XWinInfos.py in another branch.</p> <p>Thanks anyway.</p> <p>[Original Question] I am a Java/PHP/Delphi programmer and only use Python when hack someone else program -- never to write a complex Python myself. Since I have a short free time this week, I determine to write something non-trivia with Python and here is my problem</p> <p>First I have python files like this:</p> <pre><code>src/ main.py SomeUtils.py </code></pre> <p>In "SomeUtils.py, I have a few functions and one class:</p> <pre><code>... def funct1 ... def funct2 ... class MyClass1: __init__(self): self. .... ... </code></pre> <p>Then in "main.py", I use the function and class:</p> <pre><code>from SomeUtils import *; def main(): funct1(); # Use funct1 without problem; aMyObj1 = MyClass1(); # Use MyClass1 with error if (__name__ == "__main__"): main(); </code></pre> <p>The problem is that the functions are used without any problem what so ever but I cannot use the class.</p> <p>The error is:</p> <pre><code>NameError: global name 'MyClass1' is not defined </code></pre> <p>What is the problem here? and What can I do?</p> <p>EDIT: Thanks for answers for I still have problem. :( When I change the import statements to:</p> <pre><code>from SomeUtils import funct1 from SomeUtils import MyClass1 </code></pre> <p>I have this error </p> <pre><code>ImportError: cannot import name MyClass1</code></pre> <p><b>EDIT 2:----------------------------------------------------------</b></p> <p>Thanks you guys.</p> <p>I think, it may be better to post the actual code, so here it is:</p> <p>NOTE: I am aware about ";" and "(...)" but I like it this way.</p> <p>Here is the dir structure. <img src="http://dl.getdropbox.com/u/1961549/images/Python%5Fimport%5Fprolem%5Fdir%5F.png" alt="DIRS" /> as you see, I just add an empty <strong>init</strong>.py but it seems to make no different.</p> <p>Here is main.py:</p> <pre><code> from XWinInfos import GetCurrentWindowTitle; from XWinInfos import XWinInfo; def main(): print GetCurrentWindowTitle(); aXWinInfo = XWinInfo(); if (__name__ == "__main__"): main(); </code></pre> <p>Here is XWinInfos.py:</p> <pre><code>from subprocess import Popen; from subprocess import PIPE; from RegExUtils import GetTail_ofLine_withPrefix; def GetCurrentWindowID(): aXProp = Popen(["xprop", "-root"], stdout=PIPE).communicate()[0]; aLine = GetTail_ofLine_withPrefix("_NET_ACTIVE_WINDOW\(WINDOW\): window id # 0x", aXProp); return aLine; def GetCurrentWindowTitle(): aWinID = GetCurrentWindowID(); aWinTitle = GetWindowTitle(aWinID); return aWinTitle; def GetWindowTitle(pWinID): if (aWinID == None): return None aWMCtrlList = Popen(["wmctrl", "-l"], stdout=PIPE).communicate()[0]; aWinTitle = GetTail_ofLine_withPrefix("0x[0-9a-fA-F]*" + aWinID + "[ ]+[\-]?[0-9]+[ ]+[^\ ]+[ ]+", aWMCtrlList); return aWinTitle; class XWinInfo: def __init__(self): aWinID = GetCurrentWindowID(); self.WinID = pWinID; self.Title = GetWindowTitle(pWinID); </code></pre> <p>The file RegExUtils.py holds a function "GetTail_ofLine_withPrefix" which work fine so.</p> <p>If I use "from XWinInfos import *;", the error goes "NameError: global name 'XWinInfo' is not defined".</p> <p>If I use "from XWinInfos import XWinInfo;", the error goes "ImportError: cannot import name XWinInfo".</p> <p>Please helps. Thanks in advance.</p>
0
2009-09-15T15:24:20Z
1,427,899
<p>You may want to rewrite main.py as follows:</p> <pre><code>import SomeUtils as util def main(): util.funct1() # Use funct1 without problem; aMyObj1 = util.MyClass1() # Use MyClass1 with error if __name__ == "__main__": main() </code></pre> <p>A few quick notes:</p> <ul> <li>There is no need for semicolons in Python unless you have more than one statement on a line </li> <li>There is no need to wrap conditional tests in parentheses except for grouping </li> <li><code>from module import *</code> is discouraged as it pollutes the global namespace</li> </ul>
1
2009-09-15T15:31:25Z
[ "python", "import" ]
Problem with import in Python
1,427,855
<p>[Closing NOTE] Thank you everyone that trying to help me.</p> <p>I've found the problem and it have nothing to do with python understanding of mine (which is little). :p</p> <p>The problem is that I edit the wrong branch of the same project, Main.py in one branch and XWinInfos.py in another branch.</p> <p>Thanks anyway.</p> <p>[Original Question] I am a Java/PHP/Delphi programmer and only use Python when hack someone else program -- never to write a complex Python myself. Since I have a short free time this week, I determine to write something non-trivia with Python and here is my problem</p> <p>First I have python files like this:</p> <pre><code>src/ main.py SomeUtils.py </code></pre> <p>In "SomeUtils.py, I have a few functions and one class:</p> <pre><code>... def funct1 ... def funct2 ... class MyClass1: __init__(self): self. .... ... </code></pre> <p>Then in "main.py", I use the function and class:</p> <pre><code>from SomeUtils import *; def main(): funct1(); # Use funct1 without problem; aMyObj1 = MyClass1(); # Use MyClass1 with error if (__name__ == "__main__"): main(); </code></pre> <p>The problem is that the functions are used without any problem what so ever but I cannot use the class.</p> <p>The error is:</p> <pre><code>NameError: global name 'MyClass1' is not defined </code></pre> <p>What is the problem here? and What can I do?</p> <p>EDIT: Thanks for answers for I still have problem. :( When I change the import statements to:</p> <pre><code>from SomeUtils import funct1 from SomeUtils import MyClass1 </code></pre> <p>I have this error </p> <pre><code>ImportError: cannot import name MyClass1</code></pre> <p><b>EDIT 2:----------------------------------------------------------</b></p> <p>Thanks you guys.</p> <p>I think, it may be better to post the actual code, so here it is:</p> <p>NOTE: I am aware about ";" and "(...)" but I like it this way.</p> <p>Here is the dir structure. <img src="http://dl.getdropbox.com/u/1961549/images/Python%5Fimport%5Fprolem%5Fdir%5F.png" alt="DIRS" /> as you see, I just add an empty <strong>init</strong>.py but it seems to make no different.</p> <p>Here is main.py:</p> <pre><code> from XWinInfos import GetCurrentWindowTitle; from XWinInfos import XWinInfo; def main(): print GetCurrentWindowTitle(); aXWinInfo = XWinInfo(); if (__name__ == "__main__"): main(); </code></pre> <p>Here is XWinInfos.py:</p> <pre><code>from subprocess import Popen; from subprocess import PIPE; from RegExUtils import GetTail_ofLine_withPrefix; def GetCurrentWindowID(): aXProp = Popen(["xprop", "-root"], stdout=PIPE).communicate()[0]; aLine = GetTail_ofLine_withPrefix("_NET_ACTIVE_WINDOW\(WINDOW\): window id # 0x", aXProp); return aLine; def GetCurrentWindowTitle(): aWinID = GetCurrentWindowID(); aWinTitle = GetWindowTitle(aWinID); return aWinTitle; def GetWindowTitle(pWinID): if (aWinID == None): return None aWMCtrlList = Popen(["wmctrl", "-l"], stdout=PIPE).communicate()[0]; aWinTitle = GetTail_ofLine_withPrefix("0x[0-9a-fA-F]*" + aWinID + "[ ]+[\-]?[0-9]+[ ]+[^\ ]+[ ]+", aWMCtrlList); return aWinTitle; class XWinInfo: def __init__(self): aWinID = GetCurrentWindowID(); self.WinID = pWinID; self.Title = GetWindowTitle(pWinID); </code></pre> <p>The file RegExUtils.py holds a function "GetTail_ofLine_withPrefix" which work fine so.</p> <p>If I use "from XWinInfos import *;", the error goes "NameError: global name 'XWinInfo' is not defined".</p> <p>If I use "from XWinInfos import XWinInfo;", the error goes "ImportError: cannot import name XWinInfo".</p> <p>Please helps. Thanks in advance.</p>
0
2009-09-15T15:24:20Z
1,427,902
<p>I suppose you mean </p> <pre><code>from SomeUtils import * </code></pre> <p>however, that does not trigger the error for me. This works fine for me:</p> <p>SomeUtils.py</p> <pre><code>def funct1(): print 4 class MyClass1: def __init__(self): print 8 </code></pre> <p>main.py</p> <pre><code>from SomeUtils import * def main(): funct1() # Use funct1 without problem; aMyObj1 = MyClass1() # Use MyClass1 without error if (__name__ == "__main__"): main() </code></pre>
1
2009-09-15T15:31:57Z
[ "python", "import" ]
Problem with import in Python
1,427,855
<p>[Closing NOTE] Thank you everyone that trying to help me.</p> <p>I've found the problem and it have nothing to do with python understanding of mine (which is little). :p</p> <p>The problem is that I edit the wrong branch of the same project, Main.py in one branch and XWinInfos.py in another branch.</p> <p>Thanks anyway.</p> <p>[Original Question] I am a Java/PHP/Delphi programmer and only use Python when hack someone else program -- never to write a complex Python myself. Since I have a short free time this week, I determine to write something non-trivia with Python and here is my problem</p> <p>First I have python files like this:</p> <pre><code>src/ main.py SomeUtils.py </code></pre> <p>In "SomeUtils.py, I have a few functions and one class:</p> <pre><code>... def funct1 ... def funct2 ... class MyClass1: __init__(self): self. .... ... </code></pre> <p>Then in "main.py", I use the function and class:</p> <pre><code>from SomeUtils import *; def main(): funct1(); # Use funct1 without problem; aMyObj1 = MyClass1(); # Use MyClass1 with error if (__name__ == "__main__"): main(); </code></pre> <p>The problem is that the functions are used without any problem what so ever but I cannot use the class.</p> <p>The error is:</p> <pre><code>NameError: global name 'MyClass1' is not defined </code></pre> <p>What is the problem here? and What can I do?</p> <p>EDIT: Thanks for answers for I still have problem. :( When I change the import statements to:</p> <pre><code>from SomeUtils import funct1 from SomeUtils import MyClass1 </code></pre> <p>I have this error </p> <pre><code>ImportError: cannot import name MyClass1</code></pre> <p><b>EDIT 2:----------------------------------------------------------</b></p> <p>Thanks you guys.</p> <p>I think, it may be better to post the actual code, so here it is:</p> <p>NOTE: I am aware about ";" and "(...)" but I like it this way.</p> <p>Here is the dir structure. <img src="http://dl.getdropbox.com/u/1961549/images/Python%5Fimport%5Fprolem%5Fdir%5F.png" alt="DIRS" /> as you see, I just add an empty <strong>init</strong>.py but it seems to make no different.</p> <p>Here is main.py:</p> <pre><code> from XWinInfos import GetCurrentWindowTitle; from XWinInfos import XWinInfo; def main(): print GetCurrentWindowTitle(); aXWinInfo = XWinInfo(); if (__name__ == "__main__"): main(); </code></pre> <p>Here is XWinInfos.py:</p> <pre><code>from subprocess import Popen; from subprocess import PIPE; from RegExUtils import GetTail_ofLine_withPrefix; def GetCurrentWindowID(): aXProp = Popen(["xprop", "-root"], stdout=PIPE).communicate()[0]; aLine = GetTail_ofLine_withPrefix("_NET_ACTIVE_WINDOW\(WINDOW\): window id # 0x", aXProp); return aLine; def GetCurrentWindowTitle(): aWinID = GetCurrentWindowID(); aWinTitle = GetWindowTitle(aWinID); return aWinTitle; def GetWindowTitle(pWinID): if (aWinID == None): return None aWMCtrlList = Popen(["wmctrl", "-l"], stdout=PIPE).communicate()[0]; aWinTitle = GetTail_ofLine_withPrefix("0x[0-9a-fA-F]*" + aWinID + "[ ]+[\-]?[0-9]+[ ]+[^\ ]+[ ]+", aWMCtrlList); return aWinTitle; class XWinInfo: def __init__(self): aWinID = GetCurrentWindowID(); self.WinID = pWinID; self.Title = GetWindowTitle(pWinID); </code></pre> <p>The file RegExUtils.py holds a function "GetTail_ofLine_withPrefix" which work fine so.</p> <p>If I use "from XWinInfos import *;", the error goes "NameError: global name 'XWinInfo' is not defined".</p> <p>If I use "from XWinInfos import XWinInfo;", the error goes "ImportError: cannot import name XWinInfo".</p> <p>Please helps. Thanks in advance.</p>
0
2009-09-15T15:24:20Z
1,427,920
<p>Hmm... there's several typos in your example, so I wonder if your actual code has some typos as well. Here's the complete source from a quick test that does work fine without import errors.</p> <p>SomeUtils.py:</p> <pre><code>def funct1(): print('Function 1') def funct2(): print('Function 2') class MyClass1(object): def __init__(self): print('MyClass') </code></pre> <p>main.py:</p> <pre><code>from SomeUtils import * def main(): funct1() aObj = MyClass1() if (__name__ == "__main__"): main() </code></pre> <p>[EDIT Based on OP additional info]</p> <p>I still can't recreate the same error, but the code you posted won't initially work for at least a couple of errors in the XWinInfox.py <strong>init</strong> method:</p> <pre><code>self.WinID = pWinID #change to 'aWinID' since pWinID is not defined self.Title = GetWindowTitle(pWinID) #change to 'aWinID'since pWinID is not defined </code></pre> <p>so a corrected version would read:</p> <pre><code>self.WinID = aWinID self.Title = GetWindowTitle(aWinID) </code></pre> <p>Also, you have a typo in your init file name, there should be two underscores before AND after the 'init' word. Right now you have <code>'__init_.py'</code> and it should be <code>'__init__.py'</code>, however this shouldn't keep your code from working.</p> <p>Because I don't have the RegExUtils.py code, I just stubbed out the methods that rely on that file. With the stubbed methods and correcting the aforementioned typos, the code you post now works.</p>
3
2009-09-15T15:34:44Z
[ "python", "import" ]
Problem with import in Python
1,427,855
<p>[Closing NOTE] Thank you everyone that trying to help me.</p> <p>I've found the problem and it have nothing to do with python understanding of mine (which is little). :p</p> <p>The problem is that I edit the wrong branch of the same project, Main.py in one branch and XWinInfos.py in another branch.</p> <p>Thanks anyway.</p> <p>[Original Question] I am a Java/PHP/Delphi programmer and only use Python when hack someone else program -- never to write a complex Python myself. Since I have a short free time this week, I determine to write something non-trivia with Python and here is my problem</p> <p>First I have python files like this:</p> <pre><code>src/ main.py SomeUtils.py </code></pre> <p>In "SomeUtils.py, I have a few functions and one class:</p> <pre><code>... def funct1 ... def funct2 ... class MyClass1: __init__(self): self. .... ... </code></pre> <p>Then in "main.py", I use the function and class:</p> <pre><code>from SomeUtils import *; def main(): funct1(); # Use funct1 without problem; aMyObj1 = MyClass1(); # Use MyClass1 with error if (__name__ == "__main__"): main(); </code></pre> <p>The problem is that the functions are used without any problem what so ever but I cannot use the class.</p> <p>The error is:</p> <pre><code>NameError: global name 'MyClass1' is not defined </code></pre> <p>What is the problem here? and What can I do?</p> <p>EDIT: Thanks for answers for I still have problem. :( When I change the import statements to:</p> <pre><code>from SomeUtils import funct1 from SomeUtils import MyClass1 </code></pre> <p>I have this error </p> <pre><code>ImportError: cannot import name MyClass1</code></pre> <p><b>EDIT 2:----------------------------------------------------------</b></p> <p>Thanks you guys.</p> <p>I think, it may be better to post the actual code, so here it is:</p> <p>NOTE: I am aware about ";" and "(...)" but I like it this way.</p> <p>Here is the dir structure. <img src="http://dl.getdropbox.com/u/1961549/images/Python%5Fimport%5Fprolem%5Fdir%5F.png" alt="DIRS" /> as you see, I just add an empty <strong>init</strong>.py but it seems to make no different.</p> <p>Here is main.py:</p> <pre><code> from XWinInfos import GetCurrentWindowTitle; from XWinInfos import XWinInfo; def main(): print GetCurrentWindowTitle(); aXWinInfo = XWinInfo(); if (__name__ == "__main__"): main(); </code></pre> <p>Here is XWinInfos.py:</p> <pre><code>from subprocess import Popen; from subprocess import PIPE; from RegExUtils import GetTail_ofLine_withPrefix; def GetCurrentWindowID(): aXProp = Popen(["xprop", "-root"], stdout=PIPE).communicate()[0]; aLine = GetTail_ofLine_withPrefix("_NET_ACTIVE_WINDOW\(WINDOW\): window id # 0x", aXProp); return aLine; def GetCurrentWindowTitle(): aWinID = GetCurrentWindowID(); aWinTitle = GetWindowTitle(aWinID); return aWinTitle; def GetWindowTitle(pWinID): if (aWinID == None): return None aWMCtrlList = Popen(["wmctrl", "-l"], stdout=PIPE).communicate()[0]; aWinTitle = GetTail_ofLine_withPrefix("0x[0-9a-fA-F]*" + aWinID + "[ ]+[\-]?[0-9]+[ ]+[^\ ]+[ ]+", aWMCtrlList); return aWinTitle; class XWinInfo: def __init__(self): aWinID = GetCurrentWindowID(); self.WinID = pWinID; self.Title = GetWindowTitle(pWinID); </code></pre> <p>The file RegExUtils.py holds a function "GetTail_ofLine_withPrefix" which work fine so.</p> <p>If I use "from XWinInfos import *;", the error goes "NameError: global name 'XWinInfo' is not defined".</p> <p>If I use "from XWinInfos import XWinInfo;", the error goes "ImportError: cannot import name XWinInfo".</p> <p>Please helps. Thanks in advance.</p>
0
2009-09-15T15:24:20Z
1,428,131
<p>Your question is naturally linked to a lot of SO older one. See, just for reference, <a href="http://stackoverflow.com/questions/1342128/problem-with-python-and-import">SO1342128</a> and <a href="http://stackoverflow.com/questions/1057843/python-import-problem">SO1057843</a></p>
0
2009-09-15T16:12:13Z
[ "python", "import" ]
Encoding issues with python's etree.tostring
1,428,172
<p>I'm using python 2.6.2's xml.etree.cElementTree to create an xml document:</p> <pre><code>import xml.etree.cElementTree as etree elem = etree.Element('tag') elem.text = (u"Würth Elektronik Midcom").encode('utf-8') xml = etree.tostring(elem,encoding='UTF-8') </code></pre> <p>At the end of the day, xml looks like:</p> <pre><code>&lt;?xml version='1.0' encoding='UTF-8'?&gt; &lt;tag&gt;W&amp;#195;&amp;#188;rth Elektronik Midcom&lt;/tag&gt; </code></pre> <p>It looks like tostring ignored the encoding parameter and encoded 'ü' into some other character encoding ('ü' is a valid utf-8 encoding, I'm fairly sure). </p> <p>Any advice as to what I'm doing wrong would be greatly appreciated.</p>
7
2009-09-15T16:20:37Z
1,428,220
<p>You're encoding the text twice. Try this:</p> <pre><code>import xml.etree.cElementTree as etree elem = etree.Element('tag') elem.text = u"Würth Elektronik Midcom" xml = etree.tostring(elem,encoding='UTF-8') </code></pre>
16
2009-09-15T16:30:15Z
[ "python", "xml", "utf-8", "tostring" ]
python html integration
1,428,260
<p>this is a complete n00b question and i understand i may get voted down for asking this but i am totally confused over python's html integration. as i understand one way to integrate python with html code is by using mod_python. now, is there any other way or method that is more effective for using python with html?</p> <p>please advise me on this as i am new to learning python and could use some help. some pointers to code samples would be highly appreciated.</p> <p>thanks a lot.</p> <p><strong>EDIT:</strong> also what i would like to know is, how does PyHP and mod_python compare with regards to each other. i mean how are they different? and Django? what is Django all about?</p>
0
2009-09-15T16:37:27Z
1,428,306
<p>You can read a tutorial on how to use Python in the web.</p> <p><a href="http://docs.python.org/howto/webservers.html" rel="nofollow">http://docs.python.org/howto/webservers.html</a></p> <p>In few words, mod_python keeps python interpreter in memory ready to execute python scripts, which is faster than launching it every time. It doesn't let you integrate python in html like PHP. For this you need to use a special application, like PyHP (<a href="http://www.pyhp.org" rel="nofollow">http://www.pyhp.org</a>) or another (there are several of them). Read Python tutorial and documentation pages, there's plenty of info and links to many template and html-embedding engines.</p> <p>Such engines as PyHP require some overhead to run. Without them, your python application must output HTTP response headers and the page as strings. Mod_wsgi and fastcgi facilitate this process. The page I linked in the beginning gives a good overview on that.</p> <p>Also you may try Tornado, a python web server, if you don't need to stick to Apache.</p>
2
2009-09-15T16:44:34Z
[ "python", "html" ]
python html integration
1,428,260
<p>this is a complete n00b question and i understand i may get voted down for asking this but i am totally confused over python's html integration. as i understand one way to integrate python with html code is by using mod_python. now, is there any other way or method that is more effective for using python with html?</p> <p>please advise me on this as i am new to learning python and could use some help. some pointers to code samples would be highly appreciated.</p> <p>thanks a lot.</p> <p><strong>EDIT:</strong> also what i would like to know is, how does PyHP and mod_python compare with regards to each other. i mean how are they different? and Django? what is Django all about?</p>
0
2009-09-15T16:37:27Z
1,428,314
<p>I would suggest you to start with <a href="http://webpy.org/tutorial3.en" rel="nofollow">web.py</a></p>
3
2009-09-15T16:46:04Z
[ "python", "html" ]
python html integration
1,428,260
<p>this is a complete n00b question and i understand i may get voted down for asking this but i am totally confused over python's html integration. as i understand one way to integrate python with html code is by using mod_python. now, is there any other way or method that is more effective for using python with html?</p> <p>please advise me on this as i am new to learning python and could use some help. some pointers to code samples would be highly appreciated.</p> <p>thanks a lot.</p> <p><strong>EDIT:</strong> also what i would like to know is, how does PyHP and mod_python compare with regards to each other. i mean how are they different? and Django? what is Django all about?</p>
0
2009-09-15T16:37:27Z
1,428,475
<p>The standard way for Python web apps to talk to a webserver is WSGI. Also check out WebOb.</p> <ul> <li><a href="http://www.wsgi.org/wsgi/" rel="nofollow">http://www.wsgi.org/wsgi/</a></li> <li><a href="http://pythonpaste.org/webob/" rel="nofollow">http://pythonpaste.org/webob/</a></li> </ul> <p>But for a complete noob I'd start with a complete web-framework (in which case you typically can ignore the links above). Django or Grok are both full-stack framworks that are easy to use and learn. Django is more popular, but Grok is built on 13 years of Web application publishing experience, and is seriously cool. The difference is a matter of taste.</p> <ul> <li><a href="http://django.org/" rel="nofollow">http://django.org/</a></li> <li><a href="http://grok.zope.org/" rel="nofollow">http://grok.zope.org/</a></li> </ul> <p>If you want something more minimalistic, the worlds your oyster, there are an infinite amount of web frameworks for Python, from BFG to Turbogears.</p>
1
2009-09-15T17:13:28Z
[ "python", "html" ]
Python switch order of elements
1,428,547
<p>I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem:</p> <blockquote> <p>Permute the letters of a string pairwise, e.g.</p> <pre><code>input: 'abcdefgh' output: 'badcfehg' </code></pre> </blockquote>
2
2009-09-15T17:30:18Z
1,428,588
<p>I'd go for:</p> <pre><code>s="abcdefgh" print "".join(b+a for a,b in zip(s[::2],s[1::2])) </code></pre> <p>s[start:end:step] takes every step'th letter, zip matches them up pairwise, the loop swaps them, and the join gives you back a string.</p>
13
2009-09-15T17:39:11Z
[ "python" ]
Python switch order of elements
1,428,547
<p>I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem:</p> <blockquote> <p>Permute the letters of a string pairwise, e.g.</p> <pre><code>input: 'abcdefgh' output: 'badcfehg' </code></pre> </blockquote>
2
2009-09-15T17:30:18Z
1,428,604
<p>Since in Python, every string is also an iterable, <a href="http://docs.python.org/library/itertools.html" rel="nofollow">itertools</a> comes in handy here.</p> <p>In addition to the functions itertools provides, the documentation also supplies lots of recipes.</p> <pre><code>from itertools import izip_longest # From Python 2.6 docs def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --&gt; ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) </code></pre> <p>Now you can use grouper to group the string by pairs, then reverse the pairs, then join them back into a string.</p> <pre><code>pairs = grouper(2, "abcdefgh") reversed_pairs = [''.join(reversed(item)) for item in pairs] print ''.join(reversed_pairs) </code></pre>
1
2009-09-15T17:42:05Z
[ "python" ]
Python switch order of elements
1,428,547
<p>I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem:</p> <blockquote> <p>Permute the letters of a string pairwise, e.g.</p> <pre><code>input: 'abcdefgh' output: 'badcfehg' </code></pre> </blockquote>
2
2009-09-15T17:30:18Z
1,428,609
<pre><code>''.join(s[i+1] + s[i] for i in range(0,len(s),2)) </code></pre> <p>Yes, I know it's less pythonic for using range, but it's short, and I probably don't have to explain it for you to figure out what it does.</p>
5
2009-09-15T17:42:45Z
[ "python" ]
Python switch order of elements
1,428,547
<p>I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem:</p> <blockquote> <p>Permute the letters of a string pairwise, e.g.</p> <pre><code>input: 'abcdefgh' output: 'badcfehg' </code></pre> </blockquote>
2
2009-09-15T17:30:18Z
1,428,761
<p>my personal favorite to do stuff pairwise:</p> <pre><code>def pairwise( iterable ): it = iter(iterable) return zip(it, it) # zipping the same iterator twice produces pairs output = ''.join( b+a for a,b in pairwise(input)) </code></pre>
6
2009-09-15T18:04:19Z
[ "python" ]
Python switch order of elements
1,428,547
<p>I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem:</p> <blockquote> <p>Permute the letters of a string pairwise, e.g.</p> <pre><code>input: 'abcdefgh' output: 'badcfehg' </code></pre> </blockquote>
2
2009-09-15T17:30:18Z
1,429,170
<p>I just noticed that <em>none</em> of the existing answers work if the length of the input is odd. Most of the answers lose the last character. My previous answer throws an exception.</p> <p>If you just want the last character tacked onto the end, you could do something like this:</p> <pre><code>print "".join(map(lambda a,b:(b or '')+a, s[::2], s[1::2])) </code></pre> <p>or in 2.6 and later:</p> <pre><code>print "".join(b+a for a,b in izip_longest(s[::2],s[1::2], fillvalue='')) </code></pre> <p>This is based on Anthony Towns's answer, but uses either <code>map</code> or <code>izip_longest</code> to make sure the last character in an odd-length string doesn't get discarded. The <code>(b or '')</code> bit in the <code>map</code> version is to convert the <code>None</code> that <code>map</code> pads with into <code>''</code>.</p>
2
2009-09-15T19:28:13Z
[ "python" ]
Python switch order of elements
1,428,547
<p>I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem:</p> <blockquote> <p>Permute the letters of a string pairwise, e.g.</p> <pre><code>input: 'abcdefgh' output: 'badcfehg' </code></pre> </blockquote>
2
2009-09-15T17:30:18Z
1,429,303
<p>This may look a little scary, but I think you'd learn a lot deciphering the following idiom:</p> <pre><code>s = "abcdefgh" print ''.join(b+a for a,b in zip(*[iter(s)]*2)) </code></pre>
0
2009-09-15T19:55:16Z
[ "python" ]
Is it possible to make re find the smallest match while using greedy characters
1,428,780
<p>Disclaimer: I'm not a regex expert.</p> <p>I'm using Python re module to perform regex matching on many htm files. One of the patterns is something like this:</p> <pre><code>&lt;bla&gt;&lt;blabla&gt;87765.*&lt;/blabla&gt;&lt;bla&gt; </code></pre> <p>The problem I've encountered is that instead of finding all (say) five occurrences of the pattern, it will find only one. Because it welds all the occurrences into one, using the <code>&lt;bla&gt;&lt;blabla&gt;87765</code> part of the first occurrence and the <code>&lt;/blabla&gt;&lt;bla&gt;</code> part of the last occurrence in the page.</p> <p>Is there any way to tell re to find the smallest match?</p>
3
2009-09-15T18:07:11Z
1,428,802
<p>You can use a reluctant qualifier in your pattern (for more details, reference the <a href="http://docs.python.org/library/re.html">python documentation</a> on the <code>*?</code>, <code>+?</code>, and <code>??</code> operators):</p> <pre><code>&lt;bla&gt;&lt;blabla&gt;87765.*?&lt;/blabla&gt;&lt;bla&gt; </code></pre> <p>Or, exclude <code>&lt;</code> from the possible matched characters:</p> <pre><code>&lt;bla&gt;&lt;blabla&gt;87765[^&lt;]*&lt;/blabla&gt;&lt;bla&gt; </code></pre> <p><em>only</em> if there are no children tags between <code>&lt;blabla&gt;</code> and <code>&lt;/blabla&gt;</code>.</p>
10
2009-09-15T18:11:28Z
[ "python", "regex" ]
Is it possible to make re find the smallest match while using greedy characters
1,428,780
<p>Disclaimer: I'm not a regex expert.</p> <p>I'm using Python re module to perform regex matching on many htm files. One of the patterns is something like this:</p> <pre><code>&lt;bla&gt;&lt;blabla&gt;87765.*&lt;/blabla&gt;&lt;bla&gt; </code></pre> <p>The problem I've encountered is that instead of finding all (say) five occurrences of the pattern, it will find only one. Because it welds all the occurrences into one, using the <code>&lt;bla&gt;&lt;blabla&gt;87765</code> part of the first occurrence and the <code>&lt;/blabla&gt;&lt;bla&gt;</code> part of the last occurrence in the page.</p> <p>Is there any way to tell re to find the smallest match?</p>
3
2009-09-15T18:07:11Z
1,428,805
<p>Um... there is a way to tell re to find the smallest match, and it's precisely by using <em>non-greedy</em> quantifiers.</p> <pre><code>&lt;bla&gt;&lt;blabla&gt;87765.*?&lt;/blabla&gt;&lt;bla&gt; </code></pre> <p>I can't imagine why you would want to do it while using greedy quantifiers.</p>
0
2009-09-15T18:11:59Z
[ "python", "regex" ]
Is it possible to make re find the smallest match while using greedy characters
1,428,780
<p>Disclaimer: I'm not a regex expert.</p> <p>I'm using Python re module to perform regex matching on many htm files. One of the patterns is something like this:</p> <pre><code>&lt;bla&gt;&lt;blabla&gt;87765.*&lt;/blabla&gt;&lt;bla&gt; </code></pre> <p>The problem I've encountered is that instead of finding all (say) five occurrences of the pattern, it will find only one. Because it welds all the occurrences into one, using the <code>&lt;bla&gt;&lt;blabla&gt;87765</code> part of the first occurrence and the <code>&lt;/blabla&gt;&lt;bla&gt;</code> part of the last occurrence in the page.</p> <p>Is there any way to tell re to find the smallest match?</p>
3
2009-09-15T18:07:11Z
1,428,808
<p>The Python re module supports nongreedy matching. You just add a <code>?</code> to the end of the wildcard pattern, such as <code>.*?</code>. You can learn more at <a href="http://www.amk.ca/python/howto/regex/regex.html#SECTION000730000000000000000" rel="nofollow">this HOWTO</a>.</p>
1
2009-09-15T18:12:44Z
[ "python", "regex" ]
Is it possible to make re find the smallest match while using greedy characters
1,428,780
<p>Disclaimer: I'm not a regex expert.</p> <p>I'm using Python re module to perform regex matching on many htm files. One of the patterns is something like this:</p> <pre><code>&lt;bla&gt;&lt;blabla&gt;87765.*&lt;/blabla&gt;&lt;bla&gt; </code></pre> <p>The problem I've encountered is that instead of finding all (say) five occurrences of the pattern, it will find only one. Because it welds all the occurrences into one, using the <code>&lt;bla&gt;&lt;blabla&gt;87765</code> part of the first occurrence and the <code>&lt;/blabla&gt;&lt;bla&gt;</code> part of the last occurrence in the page.</p> <p>Is there any way to tell re to find the smallest match?</p>
3
2009-09-15T18:07:11Z
1,429,209
<pre><code>I believe the regex &lt;bla&gt;&lt;blabla&gt;87765.*?&lt;/blabla&gt;&lt;bla&gt; can produce catastrophic backtracking. Instead, use: &lt;bla&gt;&lt;blabla&gt;87765[^&lt;]*&lt;/blabla&gt;&lt;bla&gt; Using atomic grouping (I'm not sure Python supports this), the above regex becomes &lt;bla&gt;&lt;blabla&gt;(?&gt;(.*?&lt;))/blabla&gt;&lt;bla&gt; </code></pre> <p>Everything between (?> ... ) is treated as one single token by the regex engine, once the regex engine leaves the group. Because the entire group is one token, no backtracking can take place once the regex engine has found a match for the group. If backtracking is required, the engine has to backtrack to the regex token before the group (the caret in our example). If there is no token before the group, the regex must retry the entire regex at the next position in the string. Note that I needed to include the "&lt;" in the group to ensure atomicity. Close enough.</p>
1
2009-09-15T19:34:40Z
[ "python", "regex" ]
In Django, how to call a subprocess with a slow start-up time
1,428,900
<p>Suppose you're running Django on Linux, and you've got a view, and you want that view to return the data from a subprocess called <strong><em>cmd</em></strong> that operates on a file that the view creates, for example likeso:</p> <pre><code> def call_subprocess(request): response = HttpResponse() with tempfile.NamedTemporaryFile("W") as f: f.write(request.GET['data']) # i.e. some data # cmd operates on fname and returns output p = subprocess.Popen(["cmd", f.name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() response.write(p.out) # would be text/plain... return response </code></pre> <p>Now, suppose <strong><em>cmd</em></strong> has a very slow start-up time, but a very fast operating time, and it does not natively have a daemon mode. I would like to improve the response-time of this view.</p> <p>I would like to make the whole system would run much faster by starting up a number of instances of <strong><em>cmd</em></strong> in a worker-pool, have them wait for input, and having <strong>*call_process*</strong> ask one of those worker pool processes handle the data.</p> <p>This is really 2 parts:</p> <p>Part 1. A function that calls <strong><em>cmd</em></strong> and <strong><em>cmd</em></strong> waits for input. This could be done with pipes, i.e.</p> <pre><code>def _run_subcmd(): p = subprocess.Popen(["cmd", fname], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() # write 'out' to a tmp file o = open("out.txt", "W") o.write(out) o.close() p.close() exit() def _run_cmd(data): f = tempfile.NamedTemporaryFile("W") pipe = os.mkfifo(f.name) if os.fork() == 0: _run_subcmd(fname) else: f.write(data) r = open("out.txt", "r") out = r.read() # read 'out' from a tmp file return out def call_process(request): response = HttpResponse() out = _run_cmd(request.GET['data']) response.write(out) # would be text/plain... return response </code></pre> <p>Part 2. A set of workers running in the background that are waiting on the data. i.e. We want to extend the above so that the subprocess is already running, e.g. when the Django instance initializes, or this <strong>*call_process*</strong> is first called, a set of these workers is created</p> <pre><code>WORKER_COUNT = 6 WORKERS = [] class Worker(object): def __init__(index): self.tmp_file = tempfile.NamedTemporaryFile("W") # get a tmp file name os.mkfifo(self.tmp_file.name) self.p = subprocess.Popen(["cmd", self.tmp_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.index = index def run(out_filename, data): WORKERS[self.index] = Null # qua-mutex?? self.tmp_file.write(data) if (os.fork() == 0): # does the child have access to self.p?? out, err = self.p.communicate() o = open(out_filename, "w") o.write(out) exit() self.p.close() self.o.close() self.tmp_file.close() WORKERS[self.index] = Worker(index) # replace this one return out_file @classmethod def get_worker() # get the next worker # ... static, incrementing index </code></pre> <p>There should be some initialization of workers somewhere, like this:</p> <pre><code>def init_workers(): # create WORKERS_COUNT workers for i in xrange(0, WORKERS_COUNT): tmp_file = tempfile.NamedTemporaryFile() WORKERS.push(Worker(i)) </code></pre> <p>Now, what I have above becomes something likeso:</p> <pre><code>def _run_cmd(data): Worker.get_worker() # this needs to be atomic &amp; lock worker at Worker.index fifo = open(tempfile.NamedTemporaryFile("r")) # this stores output of cmd Worker.run(fifo.name, data) # please ignore the fact that everything will be # appended to out.txt ... these will be tmp files, too, but named elsewhere. out = fifo.read() # read 'out' from a tmp file return out def call_process(request): response = HttpResponse() out = _run_cmd(request.GET['data']) response.write(out) # would be text/plain... return response </code></pre> <p>Now, the questions:</p> <ol> <li><p>Will this work? (I've just typed this off the top of my head into StackOverflow, so I'm sure there are problems, but conceptually, will it work)</p></li> <li><p>What are the problems to look for?</p></li> <li><p>Are there better alternatives to this? e.g. Could threads work just as well (it's Debian Lenny Linux)? Are there any libraries that handle parallel process worker-pools like this?</p></li> <li><p>Are there interactions with Django that I ought to be conscious of?</p></li> </ol> <p>Thanks for reading! I hope you find this as interesting a problem as I do.</p> <p>Brian</p>
4
2009-09-15T18:29:06Z
1,430,277
<p>How about "daemonizing" the subprocess call using <a href="http://www.clapper.org/software/python/daemon/" rel="nofollow">python-daemon</a> or its successor, <a href="http://www.clapper.org/software/python/grizzled/" rel="nofollow">grizzled</a>. </p>
0
2009-09-16T00:15:06Z
[ "python", "django", "multithreading", "fork", "subprocess" ]
In Django, how to call a subprocess with a slow start-up time
1,428,900
<p>Suppose you're running Django on Linux, and you've got a view, and you want that view to return the data from a subprocess called <strong><em>cmd</em></strong> that operates on a file that the view creates, for example likeso:</p> <pre><code> def call_subprocess(request): response = HttpResponse() with tempfile.NamedTemporaryFile("W") as f: f.write(request.GET['data']) # i.e. some data # cmd operates on fname and returns output p = subprocess.Popen(["cmd", f.name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() response.write(p.out) # would be text/plain... return response </code></pre> <p>Now, suppose <strong><em>cmd</em></strong> has a very slow start-up time, but a very fast operating time, and it does not natively have a daemon mode. I would like to improve the response-time of this view.</p> <p>I would like to make the whole system would run much faster by starting up a number of instances of <strong><em>cmd</em></strong> in a worker-pool, have them wait for input, and having <strong>*call_process*</strong> ask one of those worker pool processes handle the data.</p> <p>This is really 2 parts:</p> <p>Part 1. A function that calls <strong><em>cmd</em></strong> and <strong><em>cmd</em></strong> waits for input. This could be done with pipes, i.e.</p> <pre><code>def _run_subcmd(): p = subprocess.Popen(["cmd", fname], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() # write 'out' to a tmp file o = open("out.txt", "W") o.write(out) o.close() p.close() exit() def _run_cmd(data): f = tempfile.NamedTemporaryFile("W") pipe = os.mkfifo(f.name) if os.fork() == 0: _run_subcmd(fname) else: f.write(data) r = open("out.txt", "r") out = r.read() # read 'out' from a tmp file return out def call_process(request): response = HttpResponse() out = _run_cmd(request.GET['data']) response.write(out) # would be text/plain... return response </code></pre> <p>Part 2. A set of workers running in the background that are waiting on the data. i.e. We want to extend the above so that the subprocess is already running, e.g. when the Django instance initializes, or this <strong>*call_process*</strong> is first called, a set of these workers is created</p> <pre><code>WORKER_COUNT = 6 WORKERS = [] class Worker(object): def __init__(index): self.tmp_file = tempfile.NamedTemporaryFile("W") # get a tmp file name os.mkfifo(self.tmp_file.name) self.p = subprocess.Popen(["cmd", self.tmp_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.index = index def run(out_filename, data): WORKERS[self.index] = Null # qua-mutex?? self.tmp_file.write(data) if (os.fork() == 0): # does the child have access to self.p?? out, err = self.p.communicate() o = open(out_filename, "w") o.write(out) exit() self.p.close() self.o.close() self.tmp_file.close() WORKERS[self.index] = Worker(index) # replace this one return out_file @classmethod def get_worker() # get the next worker # ... static, incrementing index </code></pre> <p>There should be some initialization of workers somewhere, like this:</p> <pre><code>def init_workers(): # create WORKERS_COUNT workers for i in xrange(0, WORKERS_COUNT): tmp_file = tempfile.NamedTemporaryFile() WORKERS.push(Worker(i)) </code></pre> <p>Now, what I have above becomes something likeso:</p> <pre><code>def _run_cmd(data): Worker.get_worker() # this needs to be atomic &amp; lock worker at Worker.index fifo = open(tempfile.NamedTemporaryFile("r")) # this stores output of cmd Worker.run(fifo.name, data) # please ignore the fact that everything will be # appended to out.txt ... these will be tmp files, too, but named elsewhere. out = fifo.read() # read 'out' from a tmp file return out def call_process(request): response = HttpResponse() out = _run_cmd(request.GET['data']) response.write(out) # would be text/plain... return response </code></pre> <p>Now, the questions:</p> <ol> <li><p>Will this work? (I've just typed this off the top of my head into StackOverflow, so I'm sure there are problems, but conceptually, will it work)</p></li> <li><p>What are the problems to look for?</p></li> <li><p>Are there better alternatives to this? e.g. Could threads work just as well (it's Debian Lenny Linux)? Are there any libraries that handle parallel process worker-pools like this?</p></li> <li><p>Are there interactions with Django that I ought to be conscious of?</p></li> </ol> <p>Thanks for reading! I hope you find this as interesting a problem as I do.</p> <p>Brian</p>
4
2009-09-15T18:29:06Z
1,431,761
<p>It may seem like i am punting this product as this is the second time i have responded with a recommendation of this.</p> <p>But it seems like you need a Message Queing service, in particular a distributed message queue.</p> <p>ere is how it will work:</p> <ol> <li>Your Django App requests CMD</li> <li>CMD gets added to a queue</li> <li>CMD gets pushed to several works</li> <li>It is executed and results returned upstream</li> </ol> <p>Most of this code exists, and you dont have to go about building your own system.</p> <p>Have a look at Celery which was initially built with Django. </p> <p><a href="http://www.celeryq.org/" rel="nofollow">http://www.celeryq.org/</a> <a href="http://robertpogorzelski.com/blog/2009/09/10/rabbitmq-celery-and-django/" rel="nofollow">http://robertpogorzelski.com/blog/2009/09/10/rabbitmq-celery-and-django/</a></p>
3
2009-09-16T08:48:24Z
[ "python", "django", "multithreading", "fork", "subprocess" ]
In Django, how to call a subprocess with a slow start-up time
1,428,900
<p>Suppose you're running Django on Linux, and you've got a view, and you want that view to return the data from a subprocess called <strong><em>cmd</em></strong> that operates on a file that the view creates, for example likeso:</p> <pre><code> def call_subprocess(request): response = HttpResponse() with tempfile.NamedTemporaryFile("W") as f: f.write(request.GET['data']) # i.e. some data # cmd operates on fname and returns output p = subprocess.Popen(["cmd", f.name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() response.write(p.out) # would be text/plain... return response </code></pre> <p>Now, suppose <strong><em>cmd</em></strong> has a very slow start-up time, but a very fast operating time, and it does not natively have a daemon mode. I would like to improve the response-time of this view.</p> <p>I would like to make the whole system would run much faster by starting up a number of instances of <strong><em>cmd</em></strong> in a worker-pool, have them wait for input, and having <strong>*call_process*</strong> ask one of those worker pool processes handle the data.</p> <p>This is really 2 parts:</p> <p>Part 1. A function that calls <strong><em>cmd</em></strong> and <strong><em>cmd</em></strong> waits for input. This could be done with pipes, i.e.</p> <pre><code>def _run_subcmd(): p = subprocess.Popen(["cmd", fname], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() # write 'out' to a tmp file o = open("out.txt", "W") o.write(out) o.close() p.close() exit() def _run_cmd(data): f = tempfile.NamedTemporaryFile("W") pipe = os.mkfifo(f.name) if os.fork() == 0: _run_subcmd(fname) else: f.write(data) r = open("out.txt", "r") out = r.read() # read 'out' from a tmp file return out def call_process(request): response = HttpResponse() out = _run_cmd(request.GET['data']) response.write(out) # would be text/plain... return response </code></pre> <p>Part 2. A set of workers running in the background that are waiting on the data. i.e. We want to extend the above so that the subprocess is already running, e.g. when the Django instance initializes, or this <strong>*call_process*</strong> is first called, a set of these workers is created</p> <pre><code>WORKER_COUNT = 6 WORKERS = [] class Worker(object): def __init__(index): self.tmp_file = tempfile.NamedTemporaryFile("W") # get a tmp file name os.mkfifo(self.tmp_file.name) self.p = subprocess.Popen(["cmd", self.tmp_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.index = index def run(out_filename, data): WORKERS[self.index] = Null # qua-mutex?? self.tmp_file.write(data) if (os.fork() == 0): # does the child have access to self.p?? out, err = self.p.communicate() o = open(out_filename, "w") o.write(out) exit() self.p.close() self.o.close() self.tmp_file.close() WORKERS[self.index] = Worker(index) # replace this one return out_file @classmethod def get_worker() # get the next worker # ... static, incrementing index </code></pre> <p>There should be some initialization of workers somewhere, like this:</p> <pre><code>def init_workers(): # create WORKERS_COUNT workers for i in xrange(0, WORKERS_COUNT): tmp_file = tempfile.NamedTemporaryFile() WORKERS.push(Worker(i)) </code></pre> <p>Now, what I have above becomes something likeso:</p> <pre><code>def _run_cmd(data): Worker.get_worker() # this needs to be atomic &amp; lock worker at Worker.index fifo = open(tempfile.NamedTemporaryFile("r")) # this stores output of cmd Worker.run(fifo.name, data) # please ignore the fact that everything will be # appended to out.txt ... these will be tmp files, too, but named elsewhere. out = fifo.read() # read 'out' from a tmp file return out def call_process(request): response = HttpResponse() out = _run_cmd(request.GET['data']) response.write(out) # would be text/plain... return response </code></pre> <p>Now, the questions:</p> <ol> <li><p>Will this work? (I've just typed this off the top of my head into StackOverflow, so I'm sure there are problems, but conceptually, will it work)</p></li> <li><p>What are the problems to look for?</p></li> <li><p>Are there better alternatives to this? e.g. Could threads work just as well (it's Debian Lenny Linux)? Are there any libraries that handle parallel process worker-pools like this?</p></li> <li><p>Are there interactions with Django that I ought to be conscious of?</p></li> </ol> <p>Thanks for reading! I hope you find this as interesting a problem as I do.</p> <p>Brian</p>
4
2009-09-15T18:29:06Z
1,445,760
<p>Issy already mentioned Celery, but since comments doesn't work well with code samples, I'll reply as an answer instead.</p> <p>You should try to use Celery synchronously with the AMQP result store. You could distribute the actual execution to another process or even another machine. Executing synchronously in celery is easy, e.g.:</p> <pre><code>&gt;&gt;&gt; from celery.task import Task &gt;&gt;&gt; from celery.registry import tasks &gt;&gt;&gt; class MyTask(Task): ... ... def run(self, x, y): ... return x * y &gt;&gt;&gt; tasks.register(MyTask) &gt;&gt;&gt; async_result = MyTask.delay(2, 2) &gt;&gt;&gt; retval = async_result.get() # Now synchronous &gt;&gt;&gt; retval 4 </code></pre> <p>The AMQP result store makes sending back the result very fast, but it's only available in the current development version (in code-freeze to become 0.8.0)</p>
3
2009-09-18T17:05:58Z
[ "python", "django", "multithreading", "fork", "subprocess" ]
Python 3 smtplib send with unicode characters
1,429,147
<p>I'm having a problem emailing unicode characters using smtplib in Python 3. This fails in 3.1.1, but works in 2.5.4:</p> <pre><code> import smtplib from email.mime.text import MIMEText sender = to = 'ABC@DEF.com' server = 'smtp.DEF.com' msg = MIMEText('€10') msg['Subject'] = 'Hello' msg['From'] = sender msg['To'] = to s = smtplib.SMTP(server) s.sendmail(sender, [to], msg.as_string()) s.quit() </code></pre> <p>I tried an example from the docs, which also failed. <a href="http://docs.python.org/3.1/library/email-examples.html" rel="nofollow">http://docs.python.org/3.1/library/email-examples.html</a>, the Send the contents of a directory as a MIME message example</p> <p>Any suggestions?</p>
7
2009-09-15T19:22:08Z
1,429,232
<p><code>_charset</code> parameter of <code>MIMEText</code> defaults to <code>us-ascii</code> according to the <a href="http://docs.python.org/library/email.mime.html#email.mime.text.MIMEText" rel="nofollow">docs</a>. Since <code>€</code> is not from us-ascii set it isn't working.</p> <p>example in the docs that you've tried clearly states: </p> <blockquote> <p>For this example, assume that the text file contains only ASCII characters.</p> </blockquote> <p>You could use <a href="http://docs.python.org/3.1/library/email.message.html#email.message.Message.get%5Fcharset" rel="nofollow"><code>.get_charset</code></a> method on your message to investigate the charset, there is incidentally <code>.set_charset</code> as well.</p>
2
2009-09-15T19:39:43Z
[ "python", "email", "unicode", "python-3.x", "smtplib" ]
Python 3 smtplib send with unicode characters
1,429,147
<p>I'm having a problem emailing unicode characters using smtplib in Python 3. This fails in 3.1.1, but works in 2.5.4:</p> <pre><code> import smtplib from email.mime.text import MIMEText sender = to = 'ABC@DEF.com' server = 'smtp.DEF.com' msg = MIMEText('€10') msg['Subject'] = 'Hello' msg['From'] = sender msg['To'] = to s = smtplib.SMTP(server) s.sendmail(sender, [to], msg.as_string()) s.quit() </code></pre> <p>I tried an example from the docs, which also failed. <a href="http://docs.python.org/3.1/library/email-examples.html" rel="nofollow">http://docs.python.org/3.1/library/email-examples.html</a>, the Send the contents of a directory as a MIME message example</p> <p>Any suggestions?</p>
7
2009-09-15T19:22:08Z
1,430,542
<p>The key is in <a href="http://docs.python.org/3.1/library/email.mime.html#email.mime.text.MIMEText" rel="nofollow">the docs</a>:</p> <pre><code>class email.mime.text.MIMEText(_text, _subtype='plain', _charset='us-ascii') </code></pre> <blockquote> <p>A subclass of MIMENonMultipart, the MIMEText class is used to create MIME objects of major type text. _text is the string for the payload. _subtype is the minor type and defaults to plain. _charset is the character set of the text and is passed as a parameter to the MIMENonMultipart constructor; it defaults to us-ascii. No guessing or encoding is performed on the text data.</p> </blockquote> <p>So what you need is clearly, <em>not</em> <code>msg = MIMEText('€10')</code>, but rather:</p> <pre><code>msg = MIMEText('€10'.encode('utf-8'), _charset='utf-8') </code></pre> <p>While not all that clearly documented, <a href="http://docs.python.org/3.1/library/smtplib.html?highlight=smtplib#smtplib.SMTP.sendmail" rel="nofollow">sendmail</a> needs a byte-string, not a Unicode one (that's what the SMTP protocol specifies); look to what <code>msg.as_string()</code> looks like for each of the two ways of building it -- given the "no guessing or encoding", your way still has that euro character in there (and no way for sendmail to turn it into a bytestring), mine doesn't (and utf-8 is clearly specified throughout).</p>
8
2009-09-16T02:00:56Z
[ "python", "email", "unicode", "python-3.x", "smtplib" ]
Python 3 smtplib send with unicode characters
1,429,147
<p>I'm having a problem emailing unicode characters using smtplib in Python 3. This fails in 3.1.1, but works in 2.5.4:</p> <pre><code> import smtplib from email.mime.text import MIMEText sender = to = 'ABC@DEF.com' server = 'smtp.DEF.com' msg = MIMEText('€10') msg['Subject'] = 'Hello' msg['From'] = sender msg['To'] = to s = smtplib.SMTP(server) s.sendmail(sender, [to], msg.as_string()) s.quit() </code></pre> <p>I tried an example from the docs, which also failed. <a href="http://docs.python.org/3.1/library/email-examples.html" rel="nofollow">http://docs.python.org/3.1/library/email-examples.html</a>, the Send the contents of a directory as a MIME message example</p> <p>Any suggestions?</p>
7
2009-09-15T19:22:08Z
2,262,800
<p>Gus Mueller had a similar issue: <a href="http://bugs.python.org/issue4403" rel="nofollow">http://bugs.python.org/issue4403</a></p>
1
2010-02-14T21:12:34Z
[ "python", "email", "unicode", "python-3.x", "smtplib" ]
Using GetExtendedTcpTable in Python
1,429,403
<p>I am trying to use GetExtendedTcpTable via a Python program. Basically I am trying to convert "ActiveState Code Recipe 392572: Using the Win32 IPHelper API" to <a href="http://www.codeproject.com/KB/IP/iphlpapi2.aspx" rel="nofollow">"Getting the active TCP/UDP connections using the GetExtendedTcpTable function"</a>. </p> <p>My problem is that I cannot seem to get the Python script to recognize TCP_TABLE_CLASS.TCP_TABL\E_OWNER_PID_ALL. </p> <p>I have tried </p> <blockquote> <p>ctypes.windll.iphlpapi.GetExtendedTcpTable(NULL, ctypes.byref(dwSize), bOrder, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0)</p> </blockquote> <p>but this always bails with "AttributeError: function 'TCP_TABLE_CLASS' not found"</p> <p>I have also tried</p> <blockquote> <p>ctypes.windll.iphlpapi.GetExtendedTcpTable(NULL, ctypes.byref(dwSize), bOrder, AF_INET, ctypes.windll.iphlpapi.TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0)</p> </blockquote> <p>which receives the same results.</p> <p>Any recommendations are appreciated.</p> <p>Cutaway</p>
0
2009-09-15T20:20:34Z
1,429,449
<p>The TCP_TABLE_CLASS is an enum</p> <pre> typedef enum { TCP_TABLE_BASIC_LISTENER, TCP_TABLE_BASIC_CONNECTIONS, TCP_TABLE_BASIC_ALL, TCP_TABLE_OWNER_PID_LISTENER, TCP_TABLE_OWNER_PID_CONNECTIONS, TCP_TABLE_OWNER_PID_ALL, TCP_TABLE_OWNER_MODULE_LISTENER, TCP_TABLE_OWNER_MODULE_CONNECTIONS, TCP_TABLE_OWNER_MODULE_ALL } TCP_TABLE_CLASS, *PTCP_TABLE_CLASS; </pre> <p>you must define it in your python script with some constants. This is not exported by the dll.</p> <pre> TCP_TABLE_BASIC_LISTENER = 0 TCP_TABLE_BASIC_CONNECTIONS = 1 TCP_TABLE_BASIC_ALL = 2 TCP_TABLE_OWNER_PID_LISTENER = 3 TCP_TABLE_OWNER_PID_CONNECTIONS = 4 TCP_TABLE_OWNER_PID_ALL = 5 TCP_TABLE_OWNER_MODULE_LISTENER = 6 TCP_TABLE_OWNER_MODULE_CONNECTIONS = 7 TCP_TABLE_OWNER_MODULE_ALL = 8 </pre>
1
2009-09-15T20:30:19Z
[ "python", "winapi" ]
Using GetExtendedTcpTable in Python
1,429,403
<p>I am trying to use GetExtendedTcpTable via a Python program. Basically I am trying to convert "ActiveState Code Recipe 392572: Using the Win32 IPHelper API" to <a href="http://www.codeproject.com/KB/IP/iphlpapi2.aspx" rel="nofollow">"Getting the active TCP/UDP connections using the GetExtendedTcpTable function"</a>. </p> <p>My problem is that I cannot seem to get the Python script to recognize TCP_TABLE_CLASS.TCP_TABL\E_OWNER_PID_ALL. </p> <p>I have tried </p> <blockquote> <p>ctypes.windll.iphlpapi.GetExtendedTcpTable(NULL, ctypes.byref(dwSize), bOrder, AF_INET, TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0)</p> </blockquote> <p>but this always bails with "AttributeError: function 'TCP_TABLE_CLASS' not found"</p> <p>I have also tried</p> <blockquote> <p>ctypes.windll.iphlpapi.GetExtendedTcpTable(NULL, ctypes.byref(dwSize), bOrder, AF_INET, ctypes.windll.iphlpapi.TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL, 0)</p> </blockquote> <p>which receives the same results.</p> <p>Any recommendations are appreciated.</p> <p>Cutaway</p>
0
2009-09-15T20:20:34Z
1,429,480
<p>In this case, since: </p> <blockquote> <p>typedef enum { TCP_TABLE_BASIC_LISTENER, TCP_TABLE_BASIC_CONNECTIONS, TCP_TABLE_BASIC_ALL, TCP_TABLE_OWNER_PID_LISTENER, TCP_TABLE_OWNER_PID_CONNECTIONS, <strong>TCP_TABLE_OWNER_PID_ALL</strong>, TCP_TABLE_OWNER_MODULE_LISTENER, TCP_TABLE_OWNER_MODULE_CONNECTIONS, TCP_TABLE_OWNER_MODULE_ALL } TCP_TABLE_CLASS, *PTCP_TABLE_CLASS;</p> </blockquote> <p>I used '5' and it worked.</p> <p>Thank you, Cutaway</p>
0
2009-09-15T20:37:03Z
[ "python", "winapi" ]
Does Python have an equivalent to 'switch'?
1,429,505
<p>I am trying to check each index in an 8 digit binary string. If it is <code>'0'</code> then it is <code>'OFF'</code> otherwise its <code>'ON'</code>.</p> <p>Is there a more concise way to write this code with a switch-like feature.?</p>
13
2009-09-15T20:41:33Z
1,429,518
<p><a href="http://docs.python.org/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python">"Why isn't there a switch or case statement in Python?"</a></p>
27
2009-09-15T20:43:18Z
[ "python", "syntax", "switch-statement" ]
Does Python have an equivalent to 'switch'?
1,429,505
<p>I am trying to check each index in an 8 digit binary string. If it is <code>'0'</code> then it is <code>'OFF'</code> otherwise its <code>'ON'</code>.</p> <p>Is there a more concise way to write this code with a switch-like feature.?</p>
13
2009-09-15T20:41:33Z
1,429,537
<p>No it doesn't. In the Python core language, one of the rules is to only have one way to do something. The switch is redundant to:</p> <pre><code>if x == 1: pass elif x == 5: pass elif x == 10: pass </code></pre> <p>(without the fall-through, of course).</p> <p>The switch was originally introduced as a compiler optimization for C. Modern compilers no longer need these hints to optimize this sort of logic statement.</p>
15
2009-09-15T20:48:50Z
[ "python", "syntax", "switch-statement" ]
Does Python have an equivalent to 'switch'?
1,429,505
<p>I am trying to check each index in an 8 digit binary string. If it is <code>'0'</code> then it is <code>'OFF'</code> otherwise its <code>'ON'</code>.</p> <p>Is there a more concise way to write this code with a switch-like feature.?</p>
13
2009-09-15T20:41:33Z
1,429,546
<p>Try this instead:</p> <pre><code>def on_function(*args, **kwargs): # do something def off_function(*args, **kwargs): # do something function_dict = { '0' : off_function, '1' : on_function } for ch in binary_string: function_dict[ch]() </code></pre> <p>Or you could use a list comprehension or generator expression if your functions return values:</p> <pre><code>result_list = [function_dict[ch]() for ch in binary_string] </code></pre>
6
2009-09-15T20:50:47Z
[ "python", "syntax", "switch-statement" ]
How to programmatically set a global (module) variable?
1,429,814
<p>I would like to define globals in a "programmatic" way. Something similar to what I want to do would be:</p> <pre><code>definitions = {'a': 1, 'b': 2, 'c': 123.4} for definition in definitions.items(): exec("%s = %r" % definition) # a = 1, etc. </code></pre> <p>Specifically, I want to create a module <code>fundamentalconstants</code> that contains variables that can be accessed as <code>fundamentalconstants.electron_mass</code>, etc., where all values are obtained through parsing a file (hence the need to do the assignments in a "programmatic" way).</p> <p>Now, the <code>exec</code> solution above would work. But I am a little bit uneasy with it, because I'm afraid that <code>exec</code> is not the cleanest way to achieve the goal of setting module globals.</p>
22
2009-09-15T21:50:47Z
1,429,835
<p>You can set globals in the dictionary returned by globals():</p> <pre><code>definitions = {'a': 1, 'b': 2, 'c': 123.4} for name, value in definitions.items(): globals()[name] = value </code></pre>
26
2009-09-15T21:56:13Z
[ "python", "module", "global-variables" ]
How to programmatically set a global (module) variable?
1,429,814
<p>I would like to define globals in a "programmatic" way. Something similar to what I want to do would be:</p> <pre><code>definitions = {'a': 1, 'b': 2, 'c': 123.4} for definition in definitions.items(): exec("%s = %r" % definition) # a = 1, etc. </code></pre> <p>Specifically, I want to create a module <code>fundamentalconstants</code> that contains variables that can be accessed as <code>fundamentalconstants.electron_mass</code>, etc., where all values are obtained through parsing a file (hence the need to do the assignments in a "programmatic" way).</p> <p>Now, the <code>exec</code> solution above would work. But I am a little bit uneasy with it, because I'm afraid that <code>exec</code> is not the cleanest way to achieve the goal of setting module globals.</p>
22
2009-09-15T21:50:47Z
1,430,039
<p>You're right, <code>exec</code> is usually a bad idea and it certainly isn't needed in this case.</p> <p>Ned's answer is fine. Another possible way to do it if you're a module is to import yourself:</p> <p>fundamentalconstants.py:</p> <pre><code>import fundamentalconstants fundamentalconstants.life_meaning= 42 for line in open('constants.dat'): name, _, value= line.partition(':') setattr(fundamentalconstants, name, value) </code></pre>
3
2009-09-15T22:49:04Z
[ "python", "module", "global-variables" ]
How to programmatically set a global (module) variable?
1,429,814
<p>I would like to define globals in a "programmatic" way. Something similar to what I want to do would be:</p> <pre><code>definitions = {'a': 1, 'b': 2, 'c': 123.4} for definition in definitions.items(): exec("%s = %r" % definition) # a = 1, etc. </code></pre> <p>Specifically, I want to create a module <code>fundamentalconstants</code> that contains variables that can be accessed as <code>fundamentalconstants.electron_mass</code>, etc., where all values are obtained through parsing a file (hence the need to do the assignments in a "programmatic" way).</p> <p>Now, the <code>exec</code> solution above would work. But I am a little bit uneasy with it, because I'm afraid that <code>exec</code> is not the cleanest way to achieve the goal of setting module globals.</p>
22
2009-09-15T21:50:47Z
1,430,178
<p>Here is a better way to do it:</p> <pre><code>import sys definitions = {'a': 1, 'b': 2, 'c': 123.4} module = sys.modules[__name__] for name, value in definitions.iteritems(): setattr(module, name, value) </code></pre>
33
2009-09-15T23:37:45Z
[ "python", "module", "global-variables" ]
Configuring Roundup with Apache
1,430,364
<p>I think I just need a bit more guidance than what the documentation gives, and it's quite hard to find anything relating to Roundup and Apache specifically.</p> <p>All i'm trying to do currently is to have Apache display what the stand-alone server does when running roundup-server support=C:/Roundup/</p> <p>Running windows XP with apache 2.2 and python 2.5 roundup 1.4.6</p> <p>I don't really have any further notes of interest, so <strong>if anyone has already got this running, could you please show me your configuration</strong> and i'll see how i go from there :) I don't expect anyone to analyse the 403 forbidden error I get before I'm sure my httpd.conf file is correct first</p> <p>Thanks in advance</p>
2
2009-09-16T00:52:31Z
1,430,601
<p>It is fairly easy to run roundup under Apache if you use <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a>.</p> <p>Unfortunately I've since moved away from roundup and no longer have a copy of my wsgi script to show you, but you should be able to figure it out from this <a href="http://markmail.org/message/y3xnnjnokjbr2rqu#query%3Aroundup%20mod%5Fwsgi+page%3A1+mid%3A3kxo57rdfqxqlgxj+state%3Aresults" rel="nofollow">mod_wgi mailing list thead</a>.</p>
1
2009-09-16T02:19:33Z
[ "python", "apache", "roundup" ]
Configuring Roundup with Apache
1,430,364
<p>I think I just need a bit more guidance than what the documentation gives, and it's quite hard to find anything relating to Roundup and Apache specifically.</p> <p>All i'm trying to do currently is to have Apache display what the stand-alone server does when running roundup-server support=C:/Roundup/</p> <p>Running windows XP with apache 2.2 and python 2.5 roundup 1.4.6</p> <p>I don't really have any further notes of interest, so <strong>if anyone has already got this running, could you please show me your configuration</strong> and i'll see how i go from there :) I don't expect anyone to analyse the 403 forbidden error I get before I'm sure my httpd.conf file is correct first</p> <p>Thanks in advance</p>
2
2009-09-16T00:52:31Z
1,431,346
<p>First, requires the following modules enabled:</p> <pre><code>LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_ajp_module modules/mod_proxy_ajp.so LoadModule proxy_balancer_module modules/mod_proxy_balancer.so LoadModule proxy_connect_module modules/mod_proxy_connect.so LoadModule proxy_ftp_module modules/mod_proxy_ftp.so LoadModule proxy_http_module modules/mod_proxy_http.so </code></pre> <p>Then, the following lines are needed to ensure any requests to /issues/ are directed to the <strong>already running</strong> roundup-server thread. Apache doesn't actually deal with the code it just passes it on! As below, i'm only worried about getting one tracker to run currently, let alone all of them as it's running on a server with other modules and I'm really not sure how to make virtual hosts work on my domain.</p> <pre><code>&lt;IfModule mod_proxy.c&gt; # proxy through one tracker ProxyPass /issues/ http://localhost:80/issues/ # proxy through all tracker(*) #ProxyPass /roundup/ http://localhost:80/ &lt;/IfModule&gt; </code></pre> <p>And that's it :) Just ensure you have roundup-server -p 8080 issues=C:/Roundup/ going on in the background and it should accept requests through Apache.</p>
3
2009-09-16T06:46:30Z
[ "python", "apache", "roundup" ]
Create a temporary FIFO (named pipe) in Python?
1,430,446
<p>How can you create a temporary FIFO (named pipe) in Python? This should work:</p> <pre><code>import tempfile temp_file_name = mktemp() os.mkfifo(temp_file_name) open(temp_file_name, os.O_WRONLY) # ... some process, somewhere, will read it ... </code></pre> <p>However, I'm hesitant because of the big warning in <a href="http://docs.python.org/library/tempfile.html">Python Docs 11.6</a> and potential removal because it's deprecated.</p> <p><strong>EDIT</strong>: It's noteworthy that I've tried <code>tempfile.NamedTemporaryFile</code> (and by extension <code>tempfile.mkstemp</code>), but <code>os.mkfifo</code> throws:</p> <blockquote> <p>OSError -17: File already exists</p> </blockquote> <p>when you run it on the files that mkstemp/NamedTemporaryFile have created.</p>
21
2009-09-16T01:16:58Z
1,430,484
<p>How about using</p> <pre><code>d = mkdtemp() t = os.path.join(d, 'fifo') </code></pre>
3
2009-09-16T01:36:12Z
[ "python", "security", "file", "fifo", "mkfifo" ]
Create a temporary FIFO (named pipe) in Python?
1,430,446
<p>How can you create a temporary FIFO (named pipe) in Python? This should work:</p> <pre><code>import tempfile temp_file_name = mktemp() os.mkfifo(temp_file_name) open(temp_file_name, os.O_WRONLY) # ... some process, somewhere, will read it ... </code></pre> <p>However, I'm hesitant because of the big warning in <a href="http://docs.python.org/library/tempfile.html">Python Docs 11.6</a> and potential removal because it's deprecated.</p> <p><strong>EDIT</strong>: It's noteworthy that I've tried <code>tempfile.NamedTemporaryFile</code> (and by extension <code>tempfile.mkstemp</code>), but <code>os.mkfifo</code> throws:</p> <blockquote> <p>OSError -17: File already exists</p> </blockquote> <p>when you run it on the files that mkstemp/NamedTemporaryFile have created.</p>
21
2009-09-16T01:16:58Z
1,430,486
<p>Why not just use <a href="http://docs.python.org/library/tempfile.html#tempfile.mkstemp" rel="nofollow">mkstemp()</a>?</p> <p>For example:</p> <pre><code>import tempfile import os handle, filename = tempfile.mkstemp() os.mkfifo(filename) writer = open(filename, os.O_WRONLY) reader = open(filename, os.O_RDONLY) os.close(handle) </code></pre>
-1
2009-09-16T01:37:37Z
[ "python", "security", "file", "fifo", "mkfifo" ]
Create a temporary FIFO (named pipe) in Python?
1,430,446
<p>How can you create a temporary FIFO (named pipe) in Python? This should work:</p> <pre><code>import tempfile temp_file_name = mktemp() os.mkfifo(temp_file_name) open(temp_file_name, os.O_WRONLY) # ... some process, somewhere, will read it ... </code></pre> <p>However, I'm hesitant because of the big warning in <a href="http://docs.python.org/library/tempfile.html">Python Docs 11.6</a> and potential removal because it's deprecated.</p> <p><strong>EDIT</strong>: It's noteworthy that I've tried <code>tempfile.NamedTemporaryFile</code> (and by extension <code>tempfile.mkstemp</code>), but <code>os.mkfifo</code> throws:</p> <blockquote> <p>OSError -17: File already exists</p> </blockquote> <p>when you run it on the files that mkstemp/NamedTemporaryFile have created.</p>
21
2009-09-16T01:16:58Z
1,430,494
<p>If it's for use within your program, and not with any externals, have a look at the <a href="http://docs.python.org/library/queue.html" rel="nofollow">Queue module</a>. As an added benefit, python queues are thread-safe.</p>
3
2009-09-16T01:42:29Z
[ "python", "security", "file", "fifo", "mkfifo" ]
Create a temporary FIFO (named pipe) in Python?
1,430,446
<p>How can you create a temporary FIFO (named pipe) in Python? This should work:</p> <pre><code>import tempfile temp_file_name = mktemp() os.mkfifo(temp_file_name) open(temp_file_name, os.O_WRONLY) # ... some process, somewhere, will read it ... </code></pre> <p>However, I'm hesitant because of the big warning in <a href="http://docs.python.org/library/tempfile.html">Python Docs 11.6</a> and potential removal because it's deprecated.</p> <p><strong>EDIT</strong>: It's noteworthy that I've tried <code>tempfile.NamedTemporaryFile</code> (and by extension <code>tempfile.mkstemp</code>), but <code>os.mkfifo</code> throws:</p> <blockquote> <p>OSError -17: File already exists</p> </blockquote> <p>when you run it on the files that mkstemp/NamedTemporaryFile have created.</p>
21
2009-09-16T01:16:58Z
1,430,566
<p><code>os.mkfifo()</code> will fail with exception <code>OSError: [Errno 17] File exists</code> if the file already exists, so there is no security issue here. The security issue with using <code>tempfile.mktemp()</code> is the race condition where it is possible for an attacker to create a file with the same name before you open it yourself, but since <code>os.mkfifo()</code> fails if the file already exists this is not a problem.</p> <p>However, since <code>mktemp()</code> is deprecated you shouldn't use it. You can use <code>tempfile.mkdtemp()</code> instead:</p> <pre><code>import os, tempfile tmpdir = tempfile.mkdtemp() filename = os.path.join(tmpdir, 'myfifo') print filename try: os.mkfifo(filename) except OSError, e: print "Failed to create FIFO: %s" % e else: fifo = open(filename, 'w') # write stuff to fifo print &gt;&gt; fifo, "hello" fifo.close() os.remove(filename) os.rmdir(tmpdir) </code></pre> <p>EDIT: I should make it clear that, just because the <code>mktemp()</code> vulnerability is averted by this, there are still the other usual security issues that need to be considered; e.g. an attacker could create the fifo (if they had suitable permissions) before your program did which could cause your program to crash if errors/exceptions are not properly handled.</p>
19
2009-09-16T02:09:15Z
[ "python", "security", "file", "fifo", "mkfifo" ]
Create a temporary FIFO (named pipe) in Python?
1,430,446
<p>How can you create a temporary FIFO (named pipe) in Python? This should work:</p> <pre><code>import tempfile temp_file_name = mktemp() os.mkfifo(temp_file_name) open(temp_file_name, os.O_WRONLY) # ... some process, somewhere, will read it ... </code></pre> <p>However, I'm hesitant because of the big warning in <a href="http://docs.python.org/library/tempfile.html">Python Docs 11.6</a> and potential removal because it's deprecated.</p> <p><strong>EDIT</strong>: It's noteworthy that I've tried <code>tempfile.NamedTemporaryFile</code> (and by extension <code>tempfile.mkstemp</code>), but <code>os.mkfifo</code> throws:</p> <blockquote> <p>OSError -17: File already exists</p> </blockquote> <p>when you run it on the files that mkstemp/NamedTemporaryFile have created.</p>
21
2009-09-16T01:16:58Z
32,597,858
<p>Effectively, all that <code>mkstemp</code> does is run <code>mktemp</code> in a loop and keeps attempting to exclusively create until it succeeds (see stdlib source code <a href="https://hg.python.org/cpython/file/2.7/Lib/tempfile.py#l235" rel="nofollow">here</a>). You can do the same with <code>os.mkfifo</code>:</p> <pre><code>import os, errno, tempfile def mkftemp(*args, **kwargs): for attempt in xrange(1024): tpath = tempfile.mktemp(*args, **kwargs) try: os.mkfifo(tpath, 0600) except OSError as e: if e.errno == errno.EEXIST: # lets try again continue else: raise else: # NOTE: we only return the path because opening with # os.open here would block indefinitely since there # isn't anyone on the other end of the fifo. return tpath else: raise IOError(errno.EEXIST, "No usable temporary file name found") </code></pre>
0
2015-09-16T00:34:37Z
[ "python", "security", "file", "fifo", "mkfifo" ]
Application to generate installers for Linux, Windows and MacOSX from a single configuration
1,430,497
<p>Here's what I want:</p> <p>Given a set of definitions (preferably in Python) on what files to install where and what post-install script to run, etc.. I would like this program to generate installers for the three major platforms:</p> <ul> <li>MSI on Windows</li> <li>dmg on MacOSX</li> <li>Tarball w/ install.sh (and rpm/deb, if possible) on Linux</li> </ul> <p>For example,</p> <p>installconfig.py:</p> <pre><code>name = 'Foo' version = '1.0' components = { 'core': {'recursive-include': 'image/' 'target_dir': '$APPDIR'} 'plugins': {'recursive-include': 'contrib/plugins', 'target_dir': '$APPDIR/plugins'} } def post_install(): ... </code></pre> <p>And I want this program to generate Foo-1.0.x86.msi, Foo-1.0.universal.dmg and Foo-1.0-linux-x86.tar.gz.</p> <p>You get the idea. Does such a program exist? (It could, under the hood, make use of WiX on Windows).</p> <p><strong>NOTE 1</strong>: <code>Foo</code> can be an application written in <em>any</em> programming language. That should not matter.</p> <p><strong>NOTE 2</strong>: Platform-specific things should be possible. For example, I should be able to specify <a href="http://wix.sourceforge.net/manual-wix2/authoring%5Fmerge%5Fmodules.htm" rel="nofollow">merge modules</a> on Windows.</p>
2
2009-09-16T01:43:44Z
1,430,520
<p>Your requirements are probably such that hand-rolling a make script to do these things is the order of the day. Or write it in python if you don't like make. It will be more flexible and probably faster than trying to learn some proprietary scripting language from some installer creator. Anything with a fancy gui and checkboxes and so on is unlikely to be able to automatically do anything rational on linux.</p>
0
2009-09-16T01:52:54Z
[ "python", "installer", "cross-platform", "wix", "dmg" ]
Application to generate installers for Linux, Windows and MacOSX from a single configuration
1,430,497
<p>Here's what I want:</p> <p>Given a set of definitions (preferably in Python) on what files to install where and what post-install script to run, etc.. I would like this program to generate installers for the three major platforms:</p> <ul> <li>MSI on Windows</li> <li>dmg on MacOSX</li> <li>Tarball w/ install.sh (and rpm/deb, if possible) on Linux</li> </ul> <p>For example,</p> <p>installconfig.py:</p> <pre><code>name = 'Foo' version = '1.0' components = { 'core': {'recursive-include': 'image/' 'target_dir': '$APPDIR'} 'plugins': {'recursive-include': 'contrib/plugins', 'target_dir': '$APPDIR/plugins'} } def post_install(): ... </code></pre> <p>And I want this program to generate Foo-1.0.x86.msi, Foo-1.0.universal.dmg and Foo-1.0-linux-x86.tar.gz.</p> <p>You get the idea. Does such a program exist? (It could, under the hood, make use of WiX on Windows).</p> <p><strong>NOTE 1</strong>: <code>Foo</code> can be an application written in <em>any</em> programming language. That should not matter.</p> <p><strong>NOTE 2</strong>: Platform-specific things should be possible. For example, I should be able to specify <a href="http://wix.sourceforge.net/manual-wix2/authoring%5Fmerge%5Fmodules.htm" rel="nofollow">merge modules</a> on Windows.</p>
2
2009-09-16T01:43:44Z
1,430,619
<p>perhaps <a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow">paver</a> can be made to meet your needs? you'd have to add the msi, dmg, tgz, etc parts as tasks using some external library, but i believe it can be done.</p>
0
2009-09-16T02:25:11Z
[ "python", "installer", "cross-platform", "wix", "dmg" ]
Application to generate installers for Linux, Windows and MacOSX from a single configuration
1,430,497
<p>Here's what I want:</p> <p>Given a set of definitions (preferably in Python) on what files to install where and what post-install script to run, etc.. I would like this program to generate installers for the three major platforms:</p> <ul> <li>MSI on Windows</li> <li>dmg on MacOSX</li> <li>Tarball w/ install.sh (and rpm/deb, if possible) on Linux</li> </ul> <p>For example,</p> <p>installconfig.py:</p> <pre><code>name = 'Foo' version = '1.0' components = { 'core': {'recursive-include': 'image/' 'target_dir': '$APPDIR'} 'plugins': {'recursive-include': 'contrib/plugins', 'target_dir': '$APPDIR/plugins'} } def post_install(): ... </code></pre> <p>And I want this program to generate Foo-1.0.x86.msi, Foo-1.0.universal.dmg and Foo-1.0-linux-x86.tar.gz.</p> <p>You get the idea. Does such a program exist? (It could, under the hood, make use of WiX on Windows).</p> <p><strong>NOTE 1</strong>: <code>Foo</code> can be an application written in <em>any</em> programming language. That should not matter.</p> <p><strong>NOTE 2</strong>: Platform-specific things should be possible. For example, I should be able to specify <a href="http://wix.sourceforge.net/manual-wix2/authoring%5Fmerge%5Fmodules.htm" rel="nofollow">merge modules</a> on Windows.</p>
2
2009-09-16T01:43:44Z
1,430,658
<p>Look into <a href="http://www.cmake.org/Wiki/CMake%3APackaging%5FWith%5FCPack" rel="nofollow">CPack</a>. It works very well with CMake, if you use that for your build system, but it also works without it. This uses CMake-type syntax, not Python, but it can generate NSIS installers, ZIP archives, binary executables on Linux, RPMs, DEBs, and Mac OS X bundles</p>
2
2009-09-16T02:38:18Z
[ "python", "installer", "cross-platform", "wix", "dmg" ]
Kill sub-threads when Django restarts?
1,430,517
<p>I'm running Django, and I'm creating threads that run in parallel while Django runs. Those threads sometimes run external processes that block while waiting for external input.</p> <p>When I restart Django, those threads that are blocking while awaiting external input sometimes persist through the restart, and further they have and keep open Port 8080 so Django can't restart.</p> <p>If I knew when Django was restarting, I could kill those threads. How can I tell when Django is restarting so that I can kill those threads (and their spawn).</p> <p>It wasn't obvious from django.utils.autoreload where any hooks may be to tell when a restart is occurring.</p> <p>Is there an alternative way to kill these threads when Django starts up?</p> <p>Thanks for reading.</p> <p>Brian</p>
0
2009-09-16T01:51:58Z
1,430,541
<p>What are you using to restart django? I'd put something in that script to look for process id's in the socket file(s) and kill those before starting django.</p> <p>Alternatively, you could be very heavy handed and just run something like 'pkill -9 *django*' before your django startup sequence.</p>
0
2009-09-16T02:00:45Z
[ "python", "django", "multithreading" ]
Kill sub-threads when Django restarts?
1,430,517
<p>I'm running Django, and I'm creating threads that run in parallel while Django runs. Those threads sometimes run external processes that block while waiting for external input.</p> <p>When I restart Django, those threads that are blocking while awaiting external input sometimes persist through the restart, and further they have and keep open Port 8080 so Django can't restart.</p> <p>If I knew when Django was restarting, I could kill those threads. How can I tell when Django is restarting so that I can kill those threads (and their spawn).</p> <p>It wasn't obvious from django.utils.autoreload where any hooks may be to tell when a restart is occurring.</p> <p>Is there an alternative way to kill these threads when Django starts up?</p> <p>Thanks for reading.</p> <p>Brian</p>
0
2009-09-16T01:51:58Z
1,430,786
<p>It's not easy for a Python process to kill its own threads -- even harder (nearly impossible) to kill the threads of <em>another</em> process, and I suspect the latter is the case you have... the "restart" is presumably happening on a different process, so those threads are more or less out of bounds for you!</p> <p>What I suggest instead is "a stitch in time saves nine": when you create those threads, make sure you set their <code>daemon</code> property to <code>True</code> (see <a href="http://docs.python.org/library/threading.html?highlight=setdaemon#threading.Thread.daemon" rel="nofollow">the docs</a> -- it's the <code>setDaemon</code> method in Python &lt;= 2.5). This way, when the main thread finishes, e.g. to restart in another process, so will the entire process (which should take all the daemon threads down, too, automatically!-)</p>
1
2009-09-16T03:26:38Z
[ "python", "django", "multithreading" ]
Load an existing many-to-many table relation with sqlalchemy
1,430,584
<p>I'm using SqlAlchemy to interact with an existing PostgreSQL database. </p> <p>I need to access data organized in a many-to-many relationship. The documentation describes how to create relationships, but I cannot find an example for neatly loading and query an existing one.</p>
1
2009-09-16T02:12:36Z
1,433,074
<p>Querying an existing relation is not really different than creating a new one. You pretty much write the same code but specify the table and column names that are already there, and of course you won't need SQLAlchemy to issue the <code>CREATE TABLE</code> statements.</p> <p>See <a href="http://www.sqlalchemy.org/docs/05/mappers.html#many-to-many" rel="nofollow">http://www.sqlalchemy.org/docs/05/mappers.html#many-to-many</a> . All you need to do is specify the foreign key columns for your existing parent, child, and association tables as in the example, and specify <code>autoload=True</code> to fill out the other fields on your Tables. If your association table stores additional information, as they almost always do, you should just break your many-to-many relation into two many-to-one relations.</p> <p>I learned SQLAlchemy while working with MySQL. With that database I always had to specify the foreign key relationships because they weren't explicit database constraints. You might get lucky and be able to reflect even more from your database, but you might prefer to use something like <a href="http://pypi.python.org/pypi/sqlautocode" rel="nofollow">http://pypi.python.org/pypi/sqlautocode</a> to just code the entire database schema and avoid the reflection delay.</p>
1
2009-09-16T13:47:02Z
[ "python", "sqlalchemy" ]
Python: Traversing a string, checking its element, and inputting dictionary key-value pairs
1,430,957
<p>I have a function that returns an 8 digit long binary string for given parameter:</p> <pre><code>def rule(x): rule = bin(x)[2:].zfill(8) return rule </code></pre> <p>I want to traverse each index of this string and check if it is a zero or a one. I tried to write a code like this: </p> <pre><code>def rule(x): rule = bin(x)[2:].zfill(8) while i &lt; len(rule(x)): if rule[i] == '0' ruleList = {i:'OFF'} elif rule[i] == '1' ruleList = {i:'ON'} i = i + 1 return ruleList </code></pre> <p>This code doesn't work. I am getting "Error: Object is unsubscriptable". What I am attempting to do is write a function that takes the following input, for example: </p> <pre><code>Input: 30 1. Converts to '00011110' (So far, so good).. 2. Checks if rule(30)[i] is '0' or '1' ('0' in this case where i = 0) 3. Then puts the result in a key value pair, where the index of the string is the key and the state (on or off) is the value. 4. The end result would be 'ruleList', where print ruleList would yield something like this: {0:'Off',1:'Off',2:'Off',3:'On',4:'On',5:'On',6:'On',7:'Off'} </code></pre> <p>Can someone help me out? I am new to python and programming in general so this function has proven to be quite challenging. I would like to see some of the more experienced coders solutions to this particular problem. </p> <p>Thanks, </p>
0
2009-09-16T04:34:57Z
1,430,984
<p>Here's a much more Pythonic version of the code you've written - hopefully the comments explain the code well enough to understand.</p> <pre><code>def rule(x): rule = bin(x)[2:].zfill(8) ruleDict = {} # create an empty dictionary for i,c in enumerate(rule): # i = index, c = character at index, for each character in rule # Leftmost bit of rule is key 0, increasing as you move right ruleDict[i] = 'OFF' if c == '0' else 'ON' # could have been written as: # if c == '0': # ruleDict[i] = 'OFF' # else: # ruleDict[i] = 'ON' # To make it so ruleDict[0] is the LSB of the number: #ruleDict[len(rule)-1-i] = 'OFF' if c == '0' else 'ON' return ruleDict print rule(30) </code></pre> <p>Output:</p> <pre><code>$ python rule.py {0: 'OFF', 1: 'ON', 2: 'ON', 3: 'ON', 4: 'ON', 5: 'OFF', 6: 'OFF', 7: 'OFF'} </code></pre> <p>The output actually <em>happens</em> to be printed in reverse order, because there is no guarantee that a dictionary's keys will be printed in any particular order. However, you will notice that the numbers correspond where the largest number is the most significant bit. That's why we had to do the funny business of indexing <code>ruleDict</code> at <code>len(rule)-1-i</code>.</p>
0
2009-09-16T04:44:47Z
[ "python" ]
Python: Traversing a string, checking its element, and inputting dictionary key-value pairs
1,430,957
<p>I have a function that returns an 8 digit long binary string for given parameter:</p> <pre><code>def rule(x): rule = bin(x)[2:].zfill(8) return rule </code></pre> <p>I want to traverse each index of this string and check if it is a zero or a one. I tried to write a code like this: </p> <pre><code>def rule(x): rule = bin(x)[2:].zfill(8) while i &lt; len(rule(x)): if rule[i] == '0' ruleList = {i:'OFF'} elif rule[i] == '1' ruleList = {i:'ON'} i = i + 1 return ruleList </code></pre> <p>This code doesn't work. I am getting "Error: Object is unsubscriptable". What I am attempting to do is write a function that takes the following input, for example: </p> <pre><code>Input: 30 1. Converts to '00011110' (So far, so good).. 2. Checks if rule(30)[i] is '0' or '1' ('0' in this case where i = 0) 3. Then puts the result in a key value pair, where the index of the string is the key and the state (on or off) is the value. 4. The end result would be 'ruleList', where print ruleList would yield something like this: {0:'Off',1:'Off',2:'Off',3:'On',4:'On',5:'On',6:'On',7:'Off'} </code></pre> <p>Can someone help me out? I am new to python and programming in general so this function has proven to be quite challenging. I would like to see some of the more experienced coders solutions to this particular problem. </p> <p>Thanks, </p>
0
2009-09-16T04:34:57Z
1,431,036
<p>Is this what you want?</p> <pre><code>def rule(x) : rule = bin(x)[2:].zfill(8) return dict((index, 'ON' if int(i) else 'OFF') for index, i in enumerate(rule)) </code></pre>
2
2009-09-16T05:04:45Z
[ "python" ]
Accessing Plist items in a dict
1,431,424
<p>I have a class in a module I that reads a plist (XML) file and returns a dict. This is extremely convenient because I can say something like:</p> <pre><code>Data.ServerNow.Property().DefaultChart </code></pre> <p>This returns a property dictionary, specifically the value for <code>DefaultChart</code>. Very elegant. However, assembling a dictionary this way fails:</p> <pre><code>dict={'Data': 'text1', 'Name':'text2', 'Place':'text3]} </code></pre> <p><code>dict</code> looks exactly like the Plist dict. But when I say</p> <pre><code>print TextNow.Data().Name </code></pre> <p>I get error</p> <pre><code> 'dict' object has no attribute 'Name' </code></pre> <p>But if I say</p> <pre><code>print TextNow.Data()['Name'] </code></pre> <p>suddenly it works!</p> <p>Can someone explain this behavior? Is there a way to convert a dict to an XML-ish dict?</p>
0
2009-09-16T07:10:04Z
1,431,776
<p>It doesn't work because the dot operator is not proper accessor syntax for python dictionaries. You;re trying to treat it as an object and access a property, rather than accessing a data member of the data structure.</p>
2
2009-09-16T08:51:00Z
[ "python", "xml", "namespaces", "plist" ]
Accessing Plist items in a dict
1,431,424
<p>I have a class in a module I that reads a plist (XML) file and returns a dict. This is extremely convenient because I can say something like:</p> <pre><code>Data.ServerNow.Property().DefaultChart </code></pre> <p>This returns a property dictionary, specifically the value for <code>DefaultChart</code>. Very elegant. However, assembling a dictionary this way fails:</p> <pre><code>dict={'Data': 'text1', 'Name':'text2', 'Place':'text3]} </code></pre> <p><code>dict</code> looks exactly like the Plist dict. But when I say</p> <pre><code>print TextNow.Data().Name </code></pre> <p>I get error</p> <pre><code> 'dict' object has no attribute 'Name' </code></pre> <p>But if I say</p> <pre><code>print TextNow.Data()['Name'] </code></pre> <p>suddenly it works!</p> <p>Can someone explain this behavior? Is there a way to convert a dict to an XML-ish dict?</p>
0
2009-09-16T07:10:04Z
1,431,828
<p>You can use getattr redefinition to treat dictionary keys as attributes, e.g.:</p> <pre><code>class xmldict(dict): def __getattr__(self, attr): try: return object.__getattribute__(self, attr) except AttributeError: if attr in self: return self[attr] else: raise </code></pre> <p>So, for example if you will have following dict:</p> <pre><code>dict_ = {'a':'some text'} </code></pre> <p>You can do so:</p> <pre><code>&gt;&gt; print xmldict(dict_).a some text &gt;&gt; print xmldict(dict_).NonExistent Traceback (most recent call last): ... AttributeError: 'xmldict' object has no attribute 'NonExistent' </code></pre>
1
2009-09-16T09:05:03Z
[ "python", "xml", "namespaces", "plist" ]
What is the keycode for control+z key in python?
1,431,495
<p>I want to send some modem AT commands using python code, and am wondering what is the keycode for the key combination <strong>control+z</strong></p> <p>Gath</p>
2
2009-09-16T07:30:23Z
1,431,524
<p>Key code? If you send AT commands you are probably sending strings with ascii text and control codes, right? Ctrl-Z is usually 26 (decimal). So chr(26) should work, or if it's a part of a string, '\x1a' as 26 decimal is 1A hex.</p> <p>That said, Ctrl-Z is not usually a part of the AT command set... so if this doesn't help you, maybe you could explain more what you are trying to do and why you would need to send Ctrl-Z.</p>
5
2009-09-16T07:38:03Z
[ "python" ]
Is it possible to run pydev connected to a virtualbox instance?
1,431,936
<p>At the moment I'm developing using a simple editor, putty, and a VirtualBox instance of a linux server. I've heard good things about pydev and would like to try it, but I'd like to use the python install &amp; terminal from my VirtualBox guest OS.</p> <p>I'm already using a Shared Folder with VirtualBox so my Guest OS can see my local files.</p> <p>Is it possible to tell pydev to use this "remote" host over SSH to execute its python-related commands?</p> <p><strong>UPDATE:</strong></p> <p>My main environment is windows, but I'd also like to be able to work this way on OS X.</p>
0
2009-09-16T09:26:45Z
1,432,066
<p>UPDATE: Let me understand the situation, Windows is hosting the virtualBox which host the linux. You connect to the linux using putty. Python files are on the linux machine and you wish to edit them from your Windows using pydev. So either do that using the sharing features of virtual box (which can work for you in vboth ways) or use ssh to edit the linux files from windows. both options would be valid for MacOSx AFAIK</p> <p>Below you cna find the way to do so over SSH</p> <p>You map a netwrok drive over SSH and then you can access the files via that drive letter see more at </p> <p><a href="http://www.neophob.com/serendipity/index.php?/archives/103-Map-a-Network-drive-net-use-over-SSH.html" rel="nofollow">http://www.neophob.com/serendipity/index.php?/archives/103-Map-a-Network-drive-net-use-over-SSH.html</a></p> <p>and</p> <p><a href="http://smithii.com/map%5Fa%5Fnetwork%5Fdrive%5Fover%5Fssh%5Fin%5Fwindows" rel="nofollow">http://smithii.com/map%5Fa%5Fnetwork%5Fdrive%5Fover%5Fssh%5Fin%5Fwindows</a></p>
0
2009-09-16T10:00:47Z
[ "python", "linux", "virtualbox", "pydev" ]
Is it possible to run pydev connected to a virtualbox instance?
1,431,936
<p>At the moment I'm developing using a simple editor, putty, and a VirtualBox instance of a linux server. I've heard good things about pydev and would like to try it, but I'd like to use the python install &amp; terminal from my VirtualBox guest OS.</p> <p>I'm already using a Shared Folder with VirtualBox so my Guest OS can see my local files.</p> <p>Is it possible to tell pydev to use this "remote" host over SSH to execute its python-related commands?</p> <p><strong>UPDATE:</strong></p> <p>My main environment is windows, but I'd also like to be able to work this way on OS X.</p>
0
2009-09-16T09:26:45Z
1,432,475
<p>I assume your host box is windows.</p> <p>I also assume that pydev will run under linux (since it's eclipse based). Are you ok installing the dev environment on your linux server?</p> <p>In which case:</p> <ol> <li>install and run <a href="http://sourceforge.net/projects/xming/" rel="nofollow">xming</a> on your windows box</li> <li>Install eclipse &amp; pydev on your linux box</li> <li>Configure <a href="http://www.math.umn.edu/systems%5Fguide/putty%5Fxwin32.html" rel="nofollow">x forwarding in putty</a></li> <li>Run pydev through putty and you'll have the UI appear on your windows machine like normal</li> </ol> <p>Then pydev will be running on the linux box quite happily, and so using the python environment on there.</p> <p>Downsides: you will need to install the X libraries &amp; java on your server (installing eclipse using your normal package manager should be enough), although you won't need to run X itself, since that's what Xming is for.</p>
1
2009-09-16T11:45:59Z
[ "python", "linux", "virtualbox", "pydev" ]
Add an "empty" option to a ChoiceField based on model datas
1,431,966
<p>I'm defining a ChoiceField based on a model's datas.</p> <pre><code>field = forms.ChoiceField(choices=[[r.id, r.name] for r in Model.objects.all()]) </code></pre> <p>However I'd like to prepend my options with an empty one to select "no" objects. But I can't find a nice way to prepend that.</p> <p>All my tests like :</p> <pre><code>field = forms.ChoiceField(choices=[[0, '----------']].extend([[r.id, r.name] for r in Model.objects.all()])) </code></pre> <p>Returns me a "NoneType object not iterable" error. The only way I've found until now is the following :</p> <pre><code>def append_empty(choices): ret = [[0, '----------']] for c in choices: ret.append(c) return ret </code></pre> <p>And when I define my field :</p> <pre><code>forms.ChoiceField(choices=append_empty([[r.id, r.name] for r in Restaurant.objects.all()]), required=False) </code></pre> <p>However I'd like to keep my code clean and not have that kind of horrors. Would you have an idea for me ? :p Thanks by advance.</p>
2
2009-09-16T09:34:08Z
1,432,100
<p>An easy answer is to do:</p> <pre><code>field = forms.ChoiceField(choices=[[0, '----------']] + [[r.id, r.name] for r in Model.objects.all()]) </code></pre> <p>Unfortunately, your approach is flawed. Even with your 'working' approach, the field choices are defined when the form is defined, not when it is instantiated - so if you add elements to the Model table, they will not appear in the choices list.</p> <p>You can avoid this by doing the allocation in the <code>__init__</code> method of your Form.</p> <p>However, there is a much easier approach. Rather than messing about with field choices dynamically, you should use the field that is specifically designed to provide choices from a model - <code>ModelChoiceField</code>. Not only does this get the list of model elements dynamically at instantiation, it already includes a blank choice by default. See <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield">the documentation</a>.</p>
8
2009-09-16T10:08:23Z
[ "python", "django", "forms", "choicefield" ]
Casting regex arguments into a list
1,431,968
<p>Greetings,</p> <p>A script is working on one or more files. I want to pass the filenames (with regex in them) as arguments and put them in a list. What is the best way to do it?</p> <p>For example I would accept the following arguments:</p> <pre><code>script.py file[1-3].nc #would create list [file1.nc, file2.nc, file3.nc] that I can work on script.py file*.nc #would scan the folder for matching patterns and create a list script.py file1.nc file15.nc booba[1-2].nc #creates [file1.nc, file15.nc, booba1.nc, booba2.nc] </code></pre>
1
2009-09-16T09:34:25Z
1,432,010
<p>Updated: Under Unix, the shell will do the example expansions you want. Under Windows it won't, and then you need to use glob.glob().</p> <p>But if you really <em>do</em> want regexp: Then you will simply have to list the directory, with listdir, and match the filenames with the regexp pattern. You'll also have to pass the parameter in quotes (at least under unix) so it doesn't expand it for you. :-)</p>
1
2009-09-16T09:44:14Z
[ "python", "regex" ]
Casting regex arguments into a list
1,431,968
<p>Greetings,</p> <p>A script is working on one or more files. I want to pass the filenames (with regex in them) as arguments and put them in a list. What is the best way to do it?</p> <p>For example I would accept the following arguments:</p> <pre><code>script.py file[1-3].nc #would create list [file1.nc, file2.nc, file3.nc] that I can work on script.py file*.nc #would scan the folder for matching patterns and create a list script.py file1.nc file15.nc booba[1-2].nc #creates [file1.nc, file15.nc, booba1.nc, booba2.nc] </code></pre>
1
2009-09-16T09:34:25Z
1,432,076
<p>The <a href="http://docs.python.org/library/glob.html" rel="nofollow">glob</a> module is exactly what you are looking for</p> <p>Check the examples:</p> <pre><code>&gt;&gt;&gt; import glob &gt;&gt;&gt; glob.glob('./[0-9].*') ['./1.gif', './2.txt'] &gt;&gt;&gt; glob.glob('*.gif') ['1.gif', 'card.gif'] &gt;&gt;&gt; glob.glob('?.gif') ['1.gif'] </code></pre> <p>You can use <a href="http://docs.python.org/library/optparse.html" rel="nofollow">optparse</a> or just sys.argv to get arguments. And pass them to glob.</p>
4
2009-09-16T10:02:21Z
[ "python", "regex" ]
In which module does the Timer class reside in python?
1,432,068
<p>Am reading the following online <a href="http://www.python.org/doc/2.5.2/lib/timer-objects.html" rel="nofollow">Timer</a> manual for python 2.5, but am wondering where is the actual module where the class Timer resides?</p> <p>Gath</p>
3
2009-09-16T10:01:05Z
1,432,074
<p>It's in the <code>threading</code> module.</p>
1
2009-09-16T10:02:20Z
[ "python", "timer" ]
In which module does the Timer class reside in python?
1,432,068
<p>Am reading the following online <a href="http://www.python.org/doc/2.5.2/lib/timer-objects.html" rel="nofollow">Timer</a> manual for python 2.5, but am wondering where is the actual module where the class Timer resides?</p> <p>Gath</p>
3
2009-09-16T10:01:05Z
1,432,125
<p>The way to figure this out: on the page you linked to, there's an Up link. It goes to the threading module.</p>
6
2009-09-16T10:13:26Z
[ "python", "timer" ]
deleting files with python scripts
1,432,122
<p>I want to delete some files with python scripts (while using Windows). I have tried the following code:</p> <pre><code>&gt;&gt;&gt;import os &gt;&gt;&gt; os.remove ('D:\new.docx') </code></pre> <p>but I am getting the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in -toplevel- os.remove ('D:\new.docx') OSError: [Errno 22] Invalid argument: 'D:\new.docx' </code></pre> <p>Can anyone here help me with this?</p> <p>THanks.</p> <p>Gillani</p>
2
2009-09-16T10:11:59Z
1,432,128
<p><code>\</code> is the escape char for python. try replacing it with <code>\\</code> .</p> <p>ex:</p> <pre><code>os.remove ('D:\\new.docx') </code></pre>
6
2009-09-16T10:13:43Z
[ "python", "file" ]
deleting files with python scripts
1,432,122
<p>I want to delete some files with python scripts (while using Windows). I have tried the following code:</p> <pre><code>&gt;&gt;&gt;import os &gt;&gt;&gt; os.remove ('D:\new.docx') </code></pre> <p>but I am getting the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#1&gt;", line 1, in -toplevel- os.remove ('D:\new.docx') OSError: [Errno 22] Invalid argument: 'D:\new.docx' </code></pre> <p>Can anyone here help me with this?</p> <p>THanks.</p> <p>Gillani</p>
2
2009-09-16T10:11:59Z
1,432,164
<p>A few options:</p> <p>Escape the <code>backslash</code>:</p> <pre><code>&gt;&gt;&gt; os.remove('D:\\new.docx') </code></pre> <p>The runtime library in Windows accepts a <code>forward slash</code> as a separator:</p> <pre><code>&gt;&gt;&gt; os.remove('D:/new.docx') </code></pre> <p><a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals">Raw string</a>:</p> <pre><code>&gt;&gt;&gt; os.remove(r'D:\new.docx') </code></pre>
6
2009-09-16T10:27:02Z
[ "python", "file" ]
how to get content of a small ascii file in python?
1,432,126
<p>Let's say we want to implement an equivalent of the PHP's <a href="http://fr2.php.net/manual/en/function.file-get-contents.php"><code>file_get_content</code></a>.</p> <p>What is the best practice? (elegant and reliable)</p> <p>Here are some proposition, are they correct?</p> <p>using <code>with</code> statement:</p> <pre><code>def file_get_contents(filename): with file(filename) as f: s = f.read() return s </code></pre> <p>is using standard <code>open()</code> safe?</p> <pre><code>def file_get_contents(filename): return open(filename).read() </code></pre> <p>What happens to file descriptor in either solution?</p>
20
2009-09-16T10:13:28Z
1,432,151
<p><code>with</code> will make sure that the file is closed when the block is left.</p> <p>In your second example, the file handle might remain open (Python makes no guarantee that it's closed or when if you don't do it explicitly).</p>
2
2009-09-16T10:21:55Z
[ "python", "file" ]
how to get content of a small ascii file in python?
1,432,126
<p>Let's say we want to implement an equivalent of the PHP's <a href="http://fr2.php.net/manual/en/function.file-get-contents.php"><code>file_get_content</code></a>.</p> <p>What is the best practice? (elegant and reliable)</p> <p>Here are some proposition, are they correct?</p> <p>using <code>with</code> statement:</p> <pre><code>def file_get_contents(filename): with file(filename) as f: s = f.read() return s </code></pre> <p>is using standard <code>open()</code> safe?</p> <pre><code>def file_get_contents(filename): return open(filename).read() </code></pre> <p>What happens to file descriptor in either solution?</p>
20
2009-09-16T10:13:28Z
1,432,169
<pre><code>import os def file_get_contents(filename): if os.path.exists(filename): fp = open(filename, "r") content = fp.read() fp.close() return content </code></pre> <p>This case it will return None if the file didn't exist, and the file descriptor will be closed before we exit the function.</p>
1
2009-09-16T10:29:12Z
[ "python", "file" ]