Questions tagged [python-2.6]
For issues that are specific to Python 2.6. If your question applies to Python in general, use the tag [python].
python-2.6
1,317
questions
656
votes
39
answers
2.2m
views
bash: pip: command not found
I downloaded pip and ran python setup.py install and everything worked just fine. The very next step in the tutorial is to run pip install <lib you want> but before it even tries to find ...
623
votes
4
answers
937k
views
Get all object attributes in Python? [duplicate]
Is there a way to get all attributes/methods/fields/etc. of an object in Python?
vars() is close to what I want, but it doesn't work unless an object has a __dict__, which isn't always true (e.g. it'...
576
votes
15
answers
894k
views
Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6
I am writing scripts in Python2.6 with use of pyVmomi and while using one of the connection methods:
service_instance = connect.SmartConnect(host=args.ip,
user=...
264
votes
5
answers
108k
views
Python try...except comma vs 'as' in except
What is the difference between ',' and 'as' in except statements, eg:
try:
pass
except Exception, exception:
pass
and:
try:
pass
except Exception as exception:
pass
Is the second ...
185
votes
10
answers
240k
views
Visibility of global variables in imported modules [duplicate]
I've run into a bit of a wall importing modules in a Python script. I'll do my best to describe the error, why I run into it, and why I'm tying this particular approach to solve my problem (which I ...
169
votes
9
answers
442k
views
How to convert a set to a list in python?
I am trying to convert a set to a list in Python 2.6. I'm using this syntax:
first_list = [1,2,3,4]
my_set=set(first_list)
my_list = list(my_set)
However, I get the following stack trace:
Traceback ...
126
votes
6
answers
107k
views
Why does sys.exit() not exit when called inside a thread in Python?
I am confused as to why the following code snippet would not exit when called in the thread, but would exit when called in the main thread.
import sys, time
from threading import Thread
def testexit()...
122
votes
13
answers
91k
views
Get class that defined method
How can I get the class that defined a method in Python?
I'd want the following example to print "__main__.FooClass":
class FooClass:
def foo_method(self):
print "foo"
class BarClass(...
121
votes
3
answers
265k
views
Pipe subprocess standard output to a variable [duplicate]
I want to run a command in pythong, using the subprocess module, and store the output in a variable. However, I do not want the command's output to be printed to the terminal.
For this code:
def ...
102
votes
6
answers
26k
views
Any gotchas using unicode_literals in Python 2.6?
We've already gotten our code base running under Python 2.6. In order to prepare for Python 3.0, we've started adding:
from __future__ import unicode_literals
into our .py files (as we modify them)....
95
votes
9
answers
301k
views
sort dict by value python [duplicate]
Assume that I have a dict.
data = {1:'b', 2:'a'}
And I want to sort data by 'b' and 'a' so I get the result
'a','b'
How do I do that?
Any ideas?
86
votes
8
answers
170k
views
How do I get Python's ElementTree to pretty print to an XML file?
Background
I am using SQLite to access a database and retrieve the desired information. I'm using ElementTree in Python version 2.6 to create an XML file with that information.
Code
import sqlite3
...
77
votes
5
answers
46k
views
Random strings in Python 2.6 (Is this OK?)
I've been trying to find a more pythonic way of generating random string in python that can scale as well. Typically, I see something similar to
''.join(random.choice(string.letters) for i in xrange(...
76
votes
21
answers
168k
views
No module named _cffi_backend
I have Python 2.6 in my Linux rhel-5. I have installed pip and required CFFI packages. When I try to run a sample CFFI program:
ffi = FFI()
it says:
File "/usr/lib/python2.6/site-packages/cffi/...
69
votes
3
answers
34k
views
How to stop Python parse_qs from parsing single values into lists?
In python 2.6, the following code:
import urlparse
qsdata = "test=test&test2=test2&test2=test3"
qs = urlparse.parse_qs(qsdata)
print qs
Gives the following output:
{'test': ['test'], 'test2'...
64
votes
3
answers
39k
views
Simple example of how to use ast.NodeVisitor?
Does anyone have a simple example using ast.NodeVisitor to walk the abstract syntax tree in Python 2.6? The difference between visit and generic_visit is unclear to me, and I cannot find any example ...
58
votes
2
answers
171k
views
pyodbc insert into sql
I use a MS SQL express db. I can connect and fetch data. But inserting data does not work:
cursor.execute("insert into [mydb].[dbo].[ConvertToolLog] ([Message]) values('test')")
I get no error but ...
54
votes
1
answer
85k
views
global variable warning in python [duplicate]
I have a python 2.6 script (yes I know I should upgrade to at least 2.7) that looks like this:
ret_code = 0
def some_func()
global ret_code
...
if __name__ == '__main__':
global ret_code
......
53
votes
3
answers
13k
views
"outsourcing" exception-handling to a decorator [closed]
Many try/except/finally-clauses not only "uglify" my code, but i find myself often using identical exception-handling for similar tasks. So i was considering reducing redundancy by "outsourcing" them ...
50
votes
14
answers
32k
views
Recursively convert python object graph to dictionary
I'm trying to convert the data from a simple object graph into a dictionary. I don't need type information or methods and I don't need to be able to convert it back to an object again.
I found this ...
50
votes
9
answers
57k
views
python histogram one-liner [duplicate]
There are many ways to write a Python program that computes a histogram.
By histogram, I mean a function that counts the occurrence of objects in an iterable and outputs the counts in a dictionary. ...
49
votes
2
answers
122k
views
Python readlines() usage and efficient practice for reading
I have a problem to parse 1000's of text files(around 3000 lines in each file of ~400KB size ) in a folder. I did read them using readlines,
for filename in os.listdir (input_dir) :
if ...
49
votes
13
answers
114k
views
How do you switch between python 2 and 3, and vice versa?
I am reading How To Learn Python The Hard Way, which uses 2. Recently discovered Invent With Python, which uses 3.
Can I download python 3, and use it when I read Invent With Python, then switch back ...
48
votes
4
answers
29k
views
List Comprehension: why is this a syntax error?
Why is print(x) here not valid (SyntaxError) in the following list-comprehension?
my_list=[1,2,3]
[print(my_item) for my_item in my_list]
To contrast - the following doesn't give a syntax error:
...
47
votes
1
answer
202k
views
How to fix symbol lookup error: undefined symbol errors in a cluster environment
I'm working on some python code that extracts some image data from an ECW file using GDAL (http://www.gdal.org/) and its python bindings. GDAL was built from source to have ECW support.
The program ...
46
votes
4
answers
176k
views
How do you get the current text contents of a QComboBox?
Using pyqt4 and python 2.6, I am using a qcombobox to provide a list of options. I am having problems with using the selected option. I have been able to use a signal to trigger a method when the ...
46
votes
8
answers
70k
views
How to get the current running module path/name
I've searched and this seems to be a simple question without a simple answer.
I have the file a/b/c.py which would be called with python -m a.b.c. I would like to obtain the value a.b.c in the module ...
45
votes
7
answers
38k
views
Python 2.6 JSON decoding performance
I'm using the json module in Python 2.6 to load and decode JSON files. However I'm currently getting slower than expected performance. I'm using a test case which is 6MB in size and json.loads() is ...
43
votes
14
answers
96k
views
How to check whether a JPEG image is color or gray scale using only Python stdlib
I have to write a test case in Python to check whether a jpg image is in color or grayscale. Can anyone please let me know if there is any way to do it with out installing extra libraries like OpenCV?
42
votes
3
answers
115k
views
Iterate through folders, then subfolders and print filenames with path to text file
I am trying to use python to create the files needed to run some other software in batch.
For part of this I need to produce a text file that loads the needed data files into the software.
My problem ...
41
votes
3
answers
12k
views
Why does Python have a format function as well as a format method
The format function in builtins seems to be like a subset of the str.format method used specifically for the case of a formatting a single object.
eg.
>>> format(13, 'x')
'd'
is ...
39
votes
1
answer
63k
views
Calling app from subprocess.call with arguments
I'm a beginner in Python, and I've been trying to call a command line app, but it fails:
>>> import subprocess as s
>>> s.call("gpio -g read 17")
Traceback (most recent call last):
...
38
votes
2
answers
141k
views
Extract time from datetime and determine if time (not date) falls within range?
The problem is that I want it to ignore the date and only factor in the time. Here is what I have:
import time
from time import mktime
from datetime import datetime
def getTimeCat(Datetime):
# ...
38
votes
2
answers
23k
views
Suppress print output in unittests
Edit: Please notice I'm using Python 2.6 (as tagged)
Say I have the following:
class Foo:
def bar(self):
print 'bar'
return 7
And say I have the following unit test:
import ...
37
votes
3
answers
50k
views
Difference between python - getmtime() and getctime() in unix system
Can someone please specify what is the difference between os.path.getmtime(path) and os.path.getctime(path) in unix systems . As per the defnition in python docs:
os.path.getmtime(path)
Return the ...
36
votes
4
answers
84k
views
If all in list == something
Using Python 2.6, is there a way to check if all the items of a sequence equals a given value, in one statement?
[pseudocode]
my_sequence = (2,5,7,82,35)
if all the values in (type(i) for i in ...
34
votes
1
answer
11k
views
Alternative to dict comprehension prior to Python 2.7
How can I make the following functionality compatible with versions of Python earlier than Python 2.7?
gwfuncs = [reboot, flush_macs, flush_cache, new_gw, revert_gw, send_log]
gw_func_dict = {...
34
votes
1
answer
82k
views
Running a python package [duplicate]
Running Python 2.6.1 on OSX, will deploy to CentOS. Would like to have a package to be invoked from a command line like this:
python [-m] tst
For that, here is the directory structure made:
$...
32
votes
4
answers
27k
views
Setup.py: install lxml with Python2.6 on CentOS
I have installed Python 2.6.6 on CentOS 5.4,
[@SC-055 lxml-2.3beta1]$ python
Python 2.6.6 (r266:84292, Jan 4 2011, 09:49:55)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "...
31
votes
8
answers
45k
views
Remove whitespaces in XML string
How can I remove the whitespaces and line breaks in an XML string in Python 2.6? I tried the following packages:
etree: This snippet keeps the original whitespaces:
xmlStr = '''<root>
<...
27
votes
4
answers
44k
views
"UnicodeEncodeError: 'ascii' codec can't encode character"
I'm trying to pass big strings of random html through regular expressions and my Python 2.6 script is choking on this:
UnicodeEncodeError: 'ascii' codec can't encode character
I traced it back to a ...
27
votes
4
answers
34k
views
Python 2.6 TreeMap/SortedDictionary?
Is there a built-in sorted dictionary implementation in Python 2.6, or are hashtables the only kind?
Clarifications:
I'm asking about sorted dictionarys, not ordered dictionaries!
24
votes
6
answers
6k
views
fabric appears to start apache2 but doesn't
I'm using fabric to remotely start a micro aws server, install git and a git repository, adjust apache config and then restart the server.
If at any point, from the fabfile I issue either
sudo('...
24
votes
3
answers
22k
views
Split long conditional expressions to lines
I have some if statements like:
def is_valid(self):
if (self.expires is None or datetime.now() < self.expires)
and (self.remains is None or self.remains > 0):
return True
...
24
votes
2
answers
16k
views
Where is documentation for multiprocessing.pool.ApplyResult?
There is frighteningly little strict API documentation (read: ZERO) for multiprocessing.pool.ApplyResult. The multiprocessing explanation doc talks about ApplyResults, but does not define them.
The ...
22
votes
3
answers
41k
views
How to install GSSAPI Python module?
I am trying to install the GSSAPI module through pip but I receive this error that I don't know how to resolve.
Could not find main GSSAPI shared library. Please try setting
GSSAPI_MAIN_LIB yourself ...
22
votes
3
answers
104k
views
Error: No matching distribution found for pip
I am trying to install pip in my python 2.6.6, I have Oracle Linux 6
I followed the answers given at this link Link
I downloaded get-pip.py file and ran the following command
sudo python2.6 get-pip....
21
votes
6
answers
7k
views
How to fix the issue "PyPI-test not found in .pypic" when submit package to PyPI?
I followed the guide How to submit a package to PyPI to submit one package.
It throwed the error below:
Traceback (most recent call last):
File "setup.py", line 27, in
'Programming ...
20
votes
2
answers
27k
views
Most pythonic way to convert a string to a octal number
I am looking to change permissions on a file with the file mask stored in a configuration file. Since os.chmod() requires an octal number, I need to convert a string to an octal number. For example:
'...
20
votes
1
answer
71k
views
How to share data between threads in this threaded TCPServer?
I'm working on a project which involves sending data over TCP. Using the ThreadedTCPServer I'm able to do that already. The server thread only needs to read incoming strings of data and set the value ...