FAQ Database Discussion Community


Formatting: multiple print statements without spaces

python,python-2.7,python-2.6,python-2.x
I'm trying to print multiple things scattered in a loop. Here is an example: print str(n)+" ", for I in range(k): print str(l)+"+", if l>4: break This gives me an out put like 10= 1+ 2+ 3+ 4 While I want it to give 10=1+2+3+4 ...

Extract the a value from this line

python,python-2.6
i know this has been asked many times before but I am struggling to extract the middle of the bellow line id1=({'children': '', 'edgeParameter': 1.0, 'id': 8, 'isOutOfDate': False, 'name': 'Datum pt-5', 'parents': '1&', 'path': 'unknown', 'sketch': 'unknown'}) The result I am trying to get is the id number. In...

Boost python multiple modules in one shared object

python,c++,boost,python-2.6,boost-python
I'm trying to create via boost python a package which will include several modules. The reasoning is that we want to expose a very large API, and it makes sense to group it in different modules for ease of use and to preserve python memory usage. On the other hand...

Chaining generators within a comprehension

python,python-2.6
Is it possible to do something like the following as a one liner in python where the resulting syntax is readable? d = dict((i,i+1) for i in range(10)) d.update((i,i+2) for i in range(20,25)) ...

Python and ElementTree: How can I nest elements/subelements in an XML?

python,xml,dictionary,python-2.6,elementtree
Background I am using Python 2.6, ElementTree, and SQLite3. My script currently does the following: Connects to a database to retrieve information from tables/schema Adds necessary data to an XML tree Outputs a (currently incorrect) XML file Code Here is how I've been retrieving schema data and adding elements to...

Scapy - Raw layer to string and into a wx.TextCtrl

unicode,wxpython,python-2.6,scapy
I'm using scapy to show all layers of a packet and when the packet has a UDP layer and Raw it sometimes gives me an 'UnicodeDecodeError: 'charmap' codec can't decode byte...' and I dont know what to do .. help? this is the line of code that makes trouble :...

How do I get Python's ElementTree to pretty print to an XML file?

python,xml,python-2.6,elementtree,pretty-print
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 import xml.etree.ElementTree as ET # NOTE: Omitted code where I acccess the database, # pull data, and add...

How can I separate and traverse data in a list of tuples in Python 2.6?

python,tuples,python-2.6
Background Updated: Here is the horrendous list I'm working with (please excuse the list's false title). The length and data is subject to change because I'm retrieving this information from an ever-changing database. Desired Outcome I will further explain my purposes because I am unsure of the best way to...

blinker does not work in Python 2.6

python,python-2.7,python-2.6,blinker
import blinker from blinker import signal class Ticket(): @classmethod def update(cls): pass ticket_created = signal('CREATED') ticket_created.connect(Ticket.update) This snippet of code works well on Python 2.7. But does not work on Python 2.6. I get this trace: Traceback (most recent call last): File "btest.py", line 10, in <module> ticket_created.connect(Ticket.update) File "/home/gavika/env2/lib/python2.6/site-packages/blinker/base.py",...

Using python 2.7. logging in python 2.6

python,python-2.7,logging,python-2.6
Is there a way to use the logging package of python 2.7 in python 2.6? There are a few things that I need like not disabling existing loggers or the dictConfig function....

Get address from PyCObject?

python,ctypes,python-2.6
I find it really strange that I couldn't an answer to this question by searching, only ever the opposite question on how to create a PyCObject from a pointer (and in C, not Python). I might just have used the wrong search terms. I have a PyCObject in Python, and...

How do I create a SELECT statement with a list as a parameter?

python,sqlite3,python-2.6
Code The following code only works when the list targets_in_sw only has one value in it: sw_current = cursor.execute("SELECT * from SOFTWARE_") sw_current = sw_current.fetchall() for sw_item in sw_current: current_software_id = sw_item[0] # Create Software XML Element sw_element = ET.SubElement(root, "Software") # Get all Targets for current sw_element targets_in_sw =...

Python - find recurring pairs/groups of values in dictionary

python,sorting,file-io,python-2.6
I have the following script, which loops over a text file of css rules, and stores each rule and its properties in a dictionary(improvements to code welcome, I've only just started using Python): findGroups.py import sys source = sys.argv[1] temp = open('pythonTestFile.txt', 'w+') di = {} with open(source, 'r') as...

Strange ElementTree remove() behaviour

python,python-2.6
I've a strange issue using elementTree while trying to remove an element, It's seem that it's just navigating and deleting only the odd elements. Here is the code import xml.etree.ElementTree as ET tree = ET.parse('bug_remove.xml') root = tree.getroot() for element in root: print element.tag print "remove all" for element in...

I want to add a string in between of 2 strings in file, but in output whole text is getting appended at the end of file

python,file-io,append,python-2.6
Code : fo = open("backup.txt", "r") filedata = fo.read() with open("backup.txt", "ab") as file : file.write(filedata[filedata.index('happy'):] + " appending text " + filedata[:filedata.rindex('ending')]) with open("backup.txt", "r") as file : print "In meddival : \n",file.read() Expected Output : I noticed that every now and then I need to Google fopen all...

What is the syntax for querying in Python?

python,sqlite3,python-2.6
I sort of understand how this works, but I get lost after the WHERE. Please tell me what is wrong with the following and help me understand what it's doing in general: myVariable = cursor.execute("SELECT TARGET_.*, TARGET_, SOFTWARE_TARGET_ WHERE" "SOFTWARE_TARGET_.SOFTWARE1=%(sw_ID)s AND" "SOFTWARE_TARGET_.TARGET2=TARGET_.ID", sw_ID=sw_ID)) I keep getting the following error: OperationalError:...

Build dictionary from string containing key=value

python,dictionary,python-2.6
I am trying to build a dictionary from a string like this: paramString = (dtoxe_n_18_cdmos=0.0000e+000, dxl_n_18_cdmos=0.0000e+000, du0_n_18_cdmos=0.0000e+000, dvth0_n_18_cdmos=0.0000e+000) I used paramDict = dict(paramString) but it Returns the error "ValueError: dictionary update sequence element #0 has length 1; 2 is required" Are perhaps the underscores in the key a Problem? Because...

Python error: EOL while scanning string literal

xml,sqlite,python-2.6,elementtree,eol
Some background information 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 Here is the code I'm using to create an XML file from the database schema. I've denoted the...

Date time format conversion in python [duplicate]

python,date,python-2.6
This question already has an answer here: Convert 12-hour date/time to 24-hour date/time 7 answers Converting string into datetime 9 answers I have a string containing time stamp in format (DD/MM/YYYY HH:MM:SS AM/PM), e.g."12/20/2014 15:25:05 pm" . The time here is in 24 Hrs format. I need to convert...

Variable with multiple entries run in a for loop

python,python-2.6
I am running python 2.6.6 and am trying to use a loop to run an snmpwalk against a variable that gets multiple entries in it. This list is populated by a different line of code that is left out and its stored as a variable. import commands import re names...

Python subprocess throws [Errno 2] No such file or directory, error generated only when it on a remote host

python,linux,ssh,subprocess,python-2.6
I'm running python 2.6. I'm getting the subprocess throws [Errno 2] No such file or directory only when I run the script via ssh. For example, if I run the script manually on the machine, there are no errors, but if I do ssh hostname script.py --host hostname it generates...

exc_value parameter from __exit__() (context manager) is string instead of Exception (Python 2.6)

python,exception,python-2.6,contextmanager
I tried to mess around with context managers and got a bit surprised when running my code with Python 2.6. Indeed, the exc_value parameter seems to be a string instead of an exception. A bit of code to hi-light this issue : import sys class contextmanager(object): def __enter__(self): pass def...

Overriding an inner function of a method in python

python,python-2.6,method-overriding
That is a kind of best practices question. I have a class structure with some methods defined. In some cases I want to override a particular part of a method. First thought on that is splitting my method to more atomic pieces and override related parts like below. class myTest(object):...

Handling socket process in a class in Python

python,multithreading,sockets,python-2.6
I am using Python 2.6 and new to sockets and threads. I need to write a socket code for listinging certain ports. Following is my related socket class: class SocketServer(object): """ """ def __init__(self, host, sock_port, buffsize=1024): self.hostname = host self.sock_port = sock_port self.buffsize = buffsize self.socket = None def...

How to get the least used item?

python,python-2.6
Say you have a defaultdict of usage counts like this: usage_counts = collections.defaultdict(int) usage_counts['foo1'] = 3 usage_counts['foo2'] = 3 usage_counts['foo3'] = 1 usage_counts['foo4'] = 1 usage_counts['foo5'] = 56 usage_counts['foo6'] = 65 And you have candidates foo1, foo3, foo4 and foo5 in some list: candidates = ['foo1', 'foo3', 'foo4', 'foo5'] How...

How do I escape colons in an attribute name with Python's ElementTree?

python,xml,escaping,python-2.6,elementtree
Background I am using ElementTree in Python version 2.6 to create an XML file (using data retrieved from a database). Code The following line of code is the problem area, as I keep getting a syntax error because of the colons within my attribute names. # Please ignore any errors...

Find multiple occuring string in array and output index

python,python-2.6
I have a array filled with e-mail addresses which change constantly. e.g. mailAddressList = ['[email protected]','[email protected]','[email protected]','[email protected]','[email protected]','[email protected]'] How do I find multiple occurrences of the same string in the array and output it's indexes?...

python way to get mounted filesystems

python,python-2.6
This is how I manage to enumerate mounted filesystems in python: for line in open("/etc/mtab"): mount_point = line.split()[1] if mount_point.startswith('/foo/bar'): ... Is there a better, cleaner or simpler way? I haven't found anything in the standard modules (os, stat, statvfs, etc)....

Removing completely isolated cells from Python array?

python,numpy,scipy,python-2.6,ndimage
I'm trying to reduce noise in a binary python array by removing all completely isolated single cells, i.e. setting "1" value cells to 0 if they are completely surrounded by other "0"s. I have been able to get a working solution by removing blobs with sizes equal to 1 using...