-
Notifications
You must be signed in to change notification settings - Fork 1
/
all_posts_clean.txt
8764 lines (6392 loc) · 348 KB
/
all_posts_clean.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Id|Title|Body
3061|"Calling a function of a module from a string with the function's name"|"What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module <code>foo</code>, and I have a string whose contents are <code>""bar""</code>. What is the best way to go about calling <code>foo.bar()</code>?
I need to get the return value of the function, which is why I don't just use <code>eval</code>. I figured out how to do it by using <code>eval</code> to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this.
"
19151|"Build a Basic Python Iterator"|"How would one create an iterative function (or iterator object) in python?
"
22617|"Format numbers to strings in Python"|"I need to find out how to format numbers as strings. My code is here:
<code>return str(hours)+"":""+str(minutes)+"":""+str(seconds)+"" ""+ampm
</code>
Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting ""5:30:59.07 pm"", it would display something like ""5.0:30.0:59.1 pm"".
Bottom line, what library / function do I need to do this for me?
"
22676|"How do I download a file over HTTP using Python?"|"I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes.
The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows <code>.bat</code> file to download the actual MP3 however. I would prefer to have the entire utility written in Python though.
I struggled though to find a way to actually down load the file in Python, thus why I resorted to <code>wget</code>.
So, how do I download the file using Python?
"
25665|"Python module for converting PDF to text"|"Which are the best Python modules to convert PDF files into text?
"
35988|"C-like structures in Python"|"Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:
<code>class MyStruct():
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
</code>
"
36139|"How to sort a list of strings?"|"What is the best way of creating an alphabetically sorted list in Python?
"
36901|"What does ** (double star) and * (star) do for parameters?"|"In the following method definitions, what does the <code>*</code> and <code>**</code> do for <code>param2</code>?
<code>def foo(param1, *param2):
def bar(param1, **param2):
</code>
"
36932|"How can I represent an 'Enum' in Python?"|"I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python?
"
38987|"How to merge two dictionaries in a single expression?"|"I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The <code>update()</code> method would be what I need, if it returned its result instead of modifying a dict in-place.
<code>>>> x = {'a':1, 'b': 2}
>>> y = {'b':10, 'c': 11}
>>> z = x.update(y)
>>> print(z)
None
>>> x
{'a': 1, 'b': 10, 'c': 11}
</code>
How can I get that final merged dict in <code>z</code>, not <code>x</code>?
(To be extra-clear, the last-one-wins conflict-handling of <code>dict.update()</code> is what I'm looking for as well.)
"
39086|"Search and replace a line in a file in Python"|"I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it.
What is the best way to do this, within the following code?
<code>f = open(file)
for line in f:
if line.contains('foo'):
newline = line.replace('foo', 'bar')
# how to write this newline back to the file
</code>
"
44778|"How would you make a comma-separated string from a list?"|"What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, <code>[ 'a', 'b', 'c' ]</code> to <code>'a,b,c'</code>? (The cases <code>[ s ]</code> and <code>[]</code> should be mapped to <code>s</code> and <code>''</code>, respectively.)
I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.
Edit: I'm both ashamed and happy that the solution is so simple. Obviously I have hardly a clue as to what I'm doing. (I probably needed ""simple"" concatenation in the past and somehow memorised <code>s.join([e1,e2,...])</code> as a shorthand for <code>s+e1+e2+...</code>.)
"
50499|"How do I get the path and name of the file that is currently executing?"|"I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.
For example, let's say I have three files. Using execfile:
<code>script_1.py</code> calls <code>script_2.py</code>.
In turn, <code>script_2.py</code> calls <code>script_3.py</code>.
How can I get the file name and path of <code>script_3.py</code>, from code within <code>script_3.py</code>, without having to pass that information as arguments from <code>script_2.py</code>?
(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)
"
51520|"How to get an absolute file path in Python"|"Given a path such as <code>""mydir/myfile.txt""</code>, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with:
<code>""C:/example/cwd/mydir/myfile.txt""
</code>
"
53162|"How can I do a line break (line continuation) in Python?"|"I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?
For example, adding a bunch of strings,
<code>e = 'a' + 'b' + 'c' + 'd'
</code>
and have it like this:
<code>e = 'a' + 'b' +
'c' + 'd'
</code>
"
53513|"Best way to check if a list,tuple or dict is empty"|"For example, if passed the following:
<code>a = []</code> or <code>a={}</code> or <code>a=()</code>
How do I check to see if <code>a</code> is empty?
"
56011|"Single quotes vs. double quotes in Python"|"According to the documentation, they're pretty much interchangeable. Is there a stylistic reason to use one over the other?
"
60208|"Replacements for switch statement in Python?"|"I want to write a function in Python that returns different fixed values based on the value of an input index.
In other languages I would use a <code>switch</code> or <code>case</code> statement, but Python does not appear to have a <code>switch</code> statement. What are the recommended Python solutions in this scenario?
"
67631|"How to import a module given the full path?"|"How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.
"
68645|"Static class variables in Python"|"Is it possible to have static class variables or methods in python? What syntax is required to do this?
"
70528|"Why are Python's 'private' methods not actually private?"|"Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this
<code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File """", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
</code>
What's the deal?!
I'll explain this a little for those who didn't quite get that.
<code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
</code>
What I did there is create a class with a public method and a private method and instantiate it.
Next, I call its public method.
<code>>>> obj.myPublicMethod()
public method
</code>
Next, I try and call its private method.
<code>>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File """", line 1, in
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
</code>
Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running dir() on the object reveals a new magical method that python creates magically for all of your 'private' methods.
<code>>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
</code>
This new method's name is always an underscore, followed by the class name, followed by the method name.
<code>>>> obj._MyClass__myPrivateMethod()
this is private!!
</code>
So much for encapsulation, eh?
In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?
"
70797|"Python: user input and commandline arguments"|"How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?
"
72852|"How to do relative imports in Python?"|"Imagine this directory structure:
<code>app/
__init__.py
sub1/
__init__.py
mod1.py
sub2/
__init__.py
mod2.py
</code>
I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it?
I tried <code>from ..sub2 import mod2</code> but I'm getting an ""Attempted relative import in non-package"".
I googled around but found only ""<code>sys.path</code> manipulation"" hacks. Isn't there a clean way?
Edit: all my <code>__init__.py</code>'s are currently empty
Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).
Edit3: The behaviour I'm looking for is the same as described in PEP 366 (thanks John B)
"
72899|"How do I sort a list of dictionaries by values of the dictionary in Python?"|"I got a list of dictionaries and want that to be sorted by a value of that dictionary.
This
<code>[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
</code>
sorted by name, should become
<code>[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
</code>
"
73663|"Terminating a Python script"|"I am aware of the <code>die()</code> command in PHP which stops a script early.
How can I do this in Python?
"
79797|"How do I convert local time to UTC in Python?"|"How do I convert a datetime string in local time to a string in UTC time?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
Clarification: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.
Also, from http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.
"
82831|"How do I check whether a file exists using Python?"|"How do I check whether a file exists, without using the <code>try</code> statement?
"
85451|"Python - time.clock() vs. time.time() - accuracy?"|"Which is better to use for timing in Python? time.clock() or time.time()? Which one provides more accuracy?
for example:
<code>start = time.clock()
... do something
elapsed = (time.clock() - start)
</code>
vs.
<code>start = time.time()
... do something
elapsed = (time.time() - start)
</code>
"
89228|"Calling an external command in Python"|"How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?
"
94935|"What is the difference between range and xrange functions in Python 2.X?"|"Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about
<code>for i in range(0, 20):
for i in xrange(0, 20):
</code>
"
100003|"What is a metaclass in Python?"|"What are metaclasses? What do you use them for?
"
101268|"Hidden features of Python"|"What are the lesser-known but useful features of the Python programming language?
Try to limit answers to Python core.
One feature per answer.
Give an example and short description of the feature, not just a link to documentation.
Label the feature using a title as the first line.
Quick links to answers:
Argument Unpacking
Braces
Chaining Comparison Operators
Decorators
Default Argument Gotchas / Dangers of Mutable Default arguments
Descriptors
Dictionary default <code>.get</code> value
Docstring Tests
Ellipsis Slicing Syntax
Enumeration
For/else
Function as iter() argument
Generator expressions
<code>import this</code>
In Place Value Swapping
List stepping
<code>__missing__</code> items
Multi-line Regex
Named string formatting
Nested list/generator comprehensions
New types at runtime
<code>.pth</code> files
ROT13 Encoding
Regex Debugging
Sending to Generators
Tab Completion in Interactive Interpreter
Ternary Expression
<code>try/except/else</code>
Unpacking+<code>print()</code> function
<code>with</code> statement
"
101754|"Is there a way to run Python on Android?"|"We are working on an S60 version and this platform has a nice Python API.
However, there is nothing official about Python on Android, but since Jython exists, is there a way to let the snake and the robot work together?
"
104420|"How to generate all permutations of a list in Python"|"How do you generate all the permutations of a list in Python, independently of the type of elements in that list?
For example:
<code>permutations([])
[]
permutations([1])
[1]
permutations([1, 2])
[1, 2]
[2, 1]
permutations([1, 2, 3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
</code>
EDIT:
Eliben pointed to a solution that's similar to mine although simpler, so I'm choosing it as the accepted answer, although Python 2.6+ has a builtin solution in the itertools module:
<code>import itertools
itertools.permutations([1, 2, 3])
</code>
"
120656|"Directory listing in Python"|"How do I get a list of all files (and directories) in a given directory in Python?
"
122327|"How do I find the location of my Python site-packages directory?"|"How do I find the location of my site-packages directory?
"
123198|"How do I copy a file in python?"|"How do I copy a file in Python? I couldn't find anything under <code>os</code>.
"
125703|"How to modify a text file?"|"I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?
"
126524|"Iterate a list with indexes in Python"|"I could swear I've seen the function (or method) that takes a list, like this <code>[3, 7, 19]</code> and makes it into iterable list of tuples, like so: <code>[(0,3), (1,7), (2,19)]</code> to use it instead of:
<code>for i in range(len(name_of_list)):
name_of_list[i] = something
</code>
but I can't remember the name and googling ""iterate list"" gets nothing.
"
127803|"How to parse an ISO 8601-formatted date?"|"I need to parse RFC 3339 strings like <code>""2008-09-03T20:56:35.450686Z""</code> into Python's <code>datetime</code> type.
I have found <code>strptime</code> in the Python standard library, but it is not very convenient.
What is the best way to do this?
"
134934|"Display number with leading zeros"|"Given:
<code>a = 1
b = 10
c = 100
</code>
I want to display a leading zero for all numbers with less than 2 digits, i.e.:
<code>01
10
100
</code>
"
136097|"What is the difference between @staticmethod and @classmethod in Python?"|"What is the difference between a function decorated with <code>@staticmethod</code> and one decorated with <code>@classmethod</code>?
"
139180|"listing all functions in a python module"|"I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.
I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in python?
eg. something like:
<code>from somemodule import foo
print foo.methods # or whatever is the correct method to call
</code>
"
145270|"Calling C/C++ from python?"|"What would be the quickest way to construct a python binding to a C or C++ library?
(using windows if this matters)
"
151199|"How do I calculate number of days betwen two dates using Python?"|"If I have two dates (ex. <code>'8/18/2008'</code> and <code>'9/26/2008'</code>) what is the best way to get the difference measured in days?
"
152580|"What's the canonical way to check for type in python?"|"What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type?
Let's say I have an object <code>o</code>. How do I check whether it's a <code>str</code>?
"
159720|"What is the naming convention in Python for variable and function names?"|"Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:
<code>// C# example
string thisIsMyVariable = ""a""
public void ThisIsMyMethod()
</code>
In Python, I have seen the above but I have also seen underscores being used:
<code># python example
this_is_my_variable = 'a'
def this_is_my_function():
</code>
Is there a more preferable, definitive coding style for Python?
"
166506|"Finding local IP addresses using Python's stdlib"|"How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?
"
172439|"How do I split a multi-line string into multiple lines?"|"I have a multi-line string literal that I want to do an operation on each line, like so:
<code>inputString = """"""Line 1
Line 2
Line 3""""""
</code>
I want to do something like the following:
<code>for line in inputString:
doStuff()
</code>
"
176011|"Python List vs. Array - when to use?"|"If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.
What is the reason or circumstance where I would want to use the array module instead?
Is it for performance and memory optimization, or am I missing something obvious?
"
176918|"Finding the index of an item given a list containing it in Python"|"For a list <code>[""foo"", ""bar"", ""baz""]</code> and an item in the list <code>""bar""</code>, what's the cleanest way to get its index (1) in Python?
"
179369|"How do I abort the execution of a Python script?"|"
Possible Duplicate:
Terminating a Python script
I have a simple Python script that I want to stop executing if a condition is met.
For example:
<code>done = True
if done:
# quit/stop/exit
else:
# do other stuff
</code>
Essentially, I am looking for something that behaves equivalently to the 'return' keyword in the body of a function which allows the flow of the code to exit the function and not execute the remaining code.
"
181530|"Styling multi-line conditions in 'if' statements?"|"Sometimes I break long conditions in <code>if</code>s onto several lines. The most obvious way to do this is:
<code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code>
Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.
For the moment I'm using:
<code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code>
But this isn't very pretty. :-)
Can you recommend an alternative way?
"
183853|"In Python 2, what is the difference between '/' and '//' when used for division?"|"Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:
<code>>>> 6/3
2
>>> 6//3
2
</code>
"
185936|"Delete Folder Contents in Python"|"How can I delete the contents of a local folder in Python?
The current project is for Windows but I would like to see *nix also.
"
191010|"How to get a complete list of object's methods and attributes?"|"<code>dir(re.compile(pattern))
</code>
does not return pattern as one of the lists's elements. Namely it returns:
<code>['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn']
</code>
According to the manual, it is supposed to contain
the object's attributes' names, the
names of its class's attributes, and
recursively of the attributes of its
class's base classes.
It says also that
The list is not necessarily complete.
Is there a way to get the complete list? I always assumed that dir returns a complete list but apparently it does not...
Also: is there a way to list only attributes? Or only methods?
Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)
"
192109|"Is there a built-in function to print all the current properties and values of an object?"|"So what I'm looking for here is something like PHP's print_r function. This is so I can debug my scripts by seeing what's the state of the object in question.
"
204017|"How do I execute a program from python? os.system fails due to spaces in path"|"I have a python script that needs to execute an external program, but for some reason fails.
If I have the following script:
<code>import os;
os.system(""C:\\Temp\\a b c\\Notepad.exe"");
raw_input();
</code>
Then it fails with the following error:
<code>'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file.
</code>
If I escape the program with quotes:
<code>import os;
os.system('""C:\\Temp\\a b c\\Notepad.exe""');
raw_input();
</code>
Then it works. However, if I add a parameter, it stops working again:
<code>import os;
os.system('""C:\\Temp\\a b c\\Notepad.exe"" ""C:\\test.txt""');
raw_input();
</code>
What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete.
Also note, moving the program to a non-spaced path is not an option either.
Edit This does not work either:
<code>import os;
os.system(""'C:\\Temp\\a b c\\Notepad.exe'"");
raw_input();
</code>
Note the swapped single/double quotes.
with or without a parameter to notepad here, it fails with the error message
<code>The filename, directory name, or volume label syntax is incorrect.
</code>
"
209513|"Convert hex string to int in Python"|"How do I convert a hex string to an int in Python?
I may have it as ""<code>0xffff</code>"" or just ""<code>ffff</code>"".
"
209840|"Map two lists into a dictionary in Python"|"Imagine that you have:
<code>keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
</code>
What is the simplest way to produce the following dictionary ?
<code>a_dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
</code>
This code works, but I'm not really proud of it :
<code>a_dict = {}
junk = map(lambda k, v: a_dict.update({k: v}), keys, values)
</code>
"
227459|"ASCII value of a character in Python"|"How do I get the ASCII value of a character as an int in Python?
"
230751|"How to flush output of Python print?"|"How do I force Python's print function to output to the screen?
This is not a duplicate of Disable output buffering - the linked question is attempting unbuffered output, while this is more general. The top answers in that question are too powerful or involved for this one (they're not good answers for this), and this question can be found on Google by a relative newbie.
"
231767|"What does the ""yield"" keyword do?"|"What is the use of the <code>yield</code> keyword in Python? What does it do?
For example, I'm trying to understand this code1:
<code>def _get_child_candidates(self, distance, min_dist, max_dist):
if self._leftchild and distance - max_dist < self._median:
yield self._leftchild
if self._rightchild and distance + max_dist >= self._median:
yield self._rightchild
</code>
And this is the caller:
<code>result, candidates = list(), [self]
while candidates:
node = candidates.pop()
distance = node._get_dist(obj)
if distance <= max_dist and distance >= min_dist:
result.extend(node._values)
candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))
return result
</code>
What happens when the method <code>_get_child_candidates</code> is called?
Is a list returned? A single element? Is it called again? When will subsequent calls stop?
1. The code comes from Jochen Schulz (jrschulz), who made a great Python library for metric spaces. This is the link to the complete source: Module mspace.
"
237079|"How to get file creation & modification date/times in Python?"|"I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.
What's the best cross-platform way to get file creation & modification date/times in Python?
"
247770|"Retrieving python module path"|"I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.
How do I retrieve a module's path in python?
"
251464|"How to get a function name as a string in Python?"|"In Python, how do I get a function name as a string without calling the function?
<code>def my_function():
pass
print get_function_name_as_string(my_function) # my_function is not in quotes
</code>
should output <code>""my_function""</code>.
Is this available in python? If not, any idea how to write <code>get_function_name_as_string</code> in Python?
"
252703|"append vs. extend"|"What's the difference between the list methods <code>append()</code> and <code>extend()</code>?
"
265960|"Best way to strip punctuation from a string in Python"|"It seems like there should be a simpler way than:
<code>import string
s = ""string. With. Punctuation?"" # Sample string
out = s.translate(string.maketrans("""",""""), string.punctuation)
</code>
Is there?
"
268272|"Getting key with maximum value in dictionary?"|"I have a <code>dictionary</code>: keys are strings, values are integers.
Example:
<code>stats = {'a':1000, 'b':3000, 'c': 100}
</code>
I'd like to get <code>'b'</code> as an answer, since it's the key with a higher value.
I did the following, using an intermediate list with reversed key-value tuples:
<code>inverse = [(value, key) for key, value in stats.items()]
print max(inverse)[1]
</code>
Is that one the better (or even more elegant) approach?
"
269795|"How do I find the location of Python module sources?"|"How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?
I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.
"
273192|"How can I create a directory if it does not exist?"|"What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:
<code>import os
file_path = ""/my/directory/filename.txt""
directory = os.path.dirname(file_path)
try:
os.stat(directory)
except:
os.mkdir(directory)
f = file(filename)
</code>
Somehow, I missed <code>os.path.exists</code> (thanks kanja, Blair, and Douglas). This is what I have now:
<code>def ensure_dir(file_path):
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
</code>
Is there a flag for ""open"", that makes this happen automatically?
"
273946|"How do I resize an image using PIL and maintain its aspect ratio?"|"Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.
"
275018|"How can I remove (chomp) a newline in Python?"|"What is the Python equivalent of Perl's <code>chomp</code> function, which removes the last character of a value?
"
279237|"Import a module from a relative path"|"How do I import a python module given its relative path?
For example, if <code>dirFoo</code> contains <code>Foo.py</code> and <code>dirBar</code>, and <code>dirBar</code> contains <code>Bar.py</code>, how do I import <code>Bar.py</code> into <code>Foo.py</code>?
Here's a visual representation:
<code>dirFoo\
Foo.py
dirBar\
Bar.py
</code>
<code>Foo</code> wishes to include <code>Bar</code>, but restructuring the folder hierarchy is not an option.
"
279561|"What is the Python equivalent of static variables inside a function?"|"What is the idiomatic Python equivalent of this C/C++ code?
<code>void foo()
{
static int counter = 0;
counter++;
printf(""counter is %d\n"", counter);
}
</code>
specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
"
280243|"Python Linked List"|"What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by <code>'(1 2 3 4 5)</code>. Python's lists, <code>[1, 2, 3, 4, 5]</code>, and tuples, <code>(1, 2, 3, 4, 5)</code>, are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with!
"
285289|"Exit codes in Python"|"I got a message saying <code>script xyz.py returned exit code 0</code>. What does this mean?
What do the exit codes in Python mean? How many are there? Which ones are important?
"
287871|"Print in terminal with colors using Python?"|"How can I output colored text to the terminal, in Python?
What is the best Unicode symbol to represent a solid block?
"
303200|"How do I remove/delete a folder that is not empty with Python?"|"I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: <code>os.remove(""/folder_name"")</code>.
What is the most effective way of removing/deleting a folder/directory that is not empty?
"
306400|"How to randomly select an item from a list?"|"Assume I have the following list:
<code>foo = ['a', 'b', 'c', 'd', 'e']
</code>
What is the simplest way to retrieve an item at random from this list?
"
307305|"Play a Sound with Python"|"What's the easiest way to play a sound file (.wav) in Python? By easiest I mean both most platform independent and requiring the least dependencies. pygame is certainly an option, but it seems overkill for just sound.
"
311627|"How to print date in a regular format in Python?"|"This is my code:
<code>import datetime
today = datetime.date.today()
print today
</code>
This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes ""wonky"". Here is the code:
<code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist
</code>
This prints the following:
<code>[datetime.date(2008, 11, 22)]
</code>
How on earth can I get just a simple date like ""2008-11-22""?
"
312443|"How do you split a list into evenly sized chunks?"|"I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.
I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.
I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.
Related question: What is the most “pythonic” way to iterate over a list in chunks?
"
319426|"How do I do a case insensitive string comparison in Python?"|"What's the best way to do case insensitive string comparison in Python?
I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged for advice.
"
323972|"Is there any way to kill a Thread in Python?"|"Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
"
328356|"Extracting text from HTML file using Python"|"I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad.
I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad.
Update <code>html2text</code> looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean.
Related questions:
Filter out HTML tags and resolve entities in python
Convert XML/HTML Entities into Unicode String in Python
"
332289|"How do you change the size of figures drawn with matplotlib?"|"How do you change the size of figure drawn with matplotlib?
"
338768|"Python error ""ImportError: No module named"""|"Python is installed in a local directory.
My directory tree looks like this:
<code>(local directory)/site-packages/toolkit/interface.py
</code>
My code is in here:
<code>(local directory)/site-packages/toolkit/examples/mountain.py
</code>
To run the example, I write <code>python mountain.py</code>, and in the code I have:
<code>from toolkit.interface import interface
</code>
And I get the error:
<code>Traceback (most recent call last):
File ""mountain.py"", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
</code>
I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>. Also, I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.
I do not know why Python cannot find the file when it is in <code>sys.path</code>. Any ideas? Can it be a permissions problem? Do I need some execution permission?
"
339007|"Nicest way to pad zeroes to string"|"What is the most pythonic way to pad a numeric string with zeroes to the left, i.e., so the numeric string has a specific length?
"
348196|"Creating a list of objects in Python"|"I'm trying to create a Python script that opens several databases and compares their contents. In the process of creating that script, I've run into a problem in creating a list whose contents are objects that I've created.
I've simplified the program to its bare bones for this posting. First I create a new class, create a new instance of it, assign it an attribute and then write it to a list. Then I assign a new value to the instance and again write it to a list... and again and again...
Problem is, it's always the same object so I'm really just changing the base object. When I read the list, I get a repeat of the same object over and over.
So how do you write objects to a list within a loop?
Thanks,
Bob J
Here's my simplified code
<code>class SimpleClass(object):
pass
x = SimpleClass
# Then create an empty list
simpleList = []
#Then loop through from 0 to 3 adding an attribute to the instance 'x' of SimpleClass
for count in range(0,4):
# each iteration creates a slightly different attribute value, and then prints it to
# prove that step is working
# but the problem is, I'm always updating a reference to 'x' and what I want to add to
# simplelist is a new instance of x that contains the updated attribute
x.attr1= '*Bob* '* count
print ""Loop Count: %s Attribute Value %s"" % (count, x.attr1)
simpleList.append(x)
print '-'*20
# And here I print out each instance of the object stored in the list 'simpleList'
# and the problem surfaces. Every element of 'simpleList' contains the same attribute value
y = SimpleClass
print ""Reading the attributes from the objects in the list""
for count in range(0,4):
y = simpleList[count]
print y.attr1
</code>
So how do I (append, extend, copy or whatever) the elements of simpleList so that each entry contains a different instance of the object instead of all pointing to the same one?
"
354038|"How do I check if a string is a number (float)?"|"What is the best possible way to check if a string can be represented as a number in Python?
The function I currently have right now is:
<code>def is_number(s):
try:
float(s)
return True
except ValueError:
return False
</code>
Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse.
"
354883|"How do you return multiple values in Python?"|"The canonical way to return multiple values in languages that support it is often tupling.
Option: Using a tuple
Consider this trivial example:
<code>def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return (y0,y1,y2)
</code>
However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.
Option: Using a dictionary
The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a <code>dict</code>.
Consider the following:
<code>def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return {'y0':y0, 'y1':y1 ,'y2':y2 }
</code>
(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)
Now, we have a mechanism whereby we can project out a particular member of the returned object. For example,
<code>result['y0']
</code>
Option: Using a class
However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:
<code>class ReturnValue(object):
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return ReturnValue(y0, y1, y2)
</code>
In python the previous two are perhaps very similar in terms of plumbing- After all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.
There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:
<code>class ReturnValue(object):
__slots__ = [""y0"", ""y1"", ""y2""]
def __init__(self, y0, y1, y2):
self.y0 = y0
self.y1 = y1
self.y2 = y2
</code>
From the Python Reference Manual:
The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.
Option: Using a list
Another suggestion which I'd overlooked comes from Bill the Lizard:
<code>def h(x):
result = [x + 1]
result.append(x * 3)
result.append(y0 ** y3)
return result
</code>
This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are mutable, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.
Question
After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?
I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel implied interfaces should be preferred to explicit interfaces, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning.
So, how do -you- return multiple values in Python?
"
364621|"How to get item's position in a list?"|"I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?
Example: