I use the python requests module to get XML from the TeamCity rest api that looks like this:
<triggers count="10">
<trigger id="TRIGGER_1240" type="buildDependencyTrigger">
<properties count="2">
<property name="afterSuccessfulBuildOnly" value="true"/>
<property name="dependsOn" value="bt191"/>
</properties>
</trigger>
<trigger id="TRIGGER_1241" type="buildDependencyTrigger">
<properties count="2">
<property name="afterSuccessfulBuildOnly" value="true"/>
<property name="dependsOn" value="bt171"/>
</properties>
</trigger>
<trigger id="TRIGGER_1242" type="buildDependencyTrigger">
<properties count="2">
<property name="afterSuccessfulBuildOnly" value="true"/>
<property name="dependsOn" value="bt167"/>
</properties>
</trigger>
<trigger id="TRIGGER_1243" type="buildDependencyTrigger">
<properties count="2">
<property name="afterSuccessfulBuildOnly" value="true"/>
<property name="dependsOn" value="bt164"/>
</properties>
</trigger>
<trigger id="TRIGGER_1244" type="buildDependencyTrigger">
<properties count="2">
<property name="afterSuccessfulBuildOnly" value="true"/>
<property name="dependsOn" value="bt364"/>
</properties>
</trigger>
<trigger id="TRIGGER_736" type="buildDependencyTrigger">
<properties count="2">
<property name="afterSuccessfulBuildOnly" value="true"/>
<property name="dependsOn" value="Components_Ratchetdb"/>
</properties>
</trigger>
<trigger id="TRIGGER_149" type="buildDependencyTrigger">
<properties count="2">
<property name="afterSuccessfulBuildOnly" value="true"/>
<property name="dependsOn" value="Components_Filedb"/>
</properties>
</trigger>
<trigger id="TRIGGER_150" type="buildDependencyTrigger">
<properties count="2">
<property name="afterSuccessfulBuildOnly" value="true"/>
<property name="dependsOn" value="bt168"/>
</properties>
</trigger>
<trigger id="TRIGGER_1130" type="buildDependencyTrigger">
<properties count="2">
<property name="afterSuccessfulBuildOnly" value="true"/>
<property name="dependsOn" value="Components_Tbldb"/>
</properties>
</trigger>
<trigger id="vcsTrigger" type="vcsTrigger" inherited="true">
<properties count="3">
<property name="quietPeriod" value="60"/>
<property name="quietPeriodMode" value="USE_DEFAULT"/>
<property name="triggerRules" value="-:version.properties
-:comment=^Incremented:**
-:**/*-schema.sql"/>
</properties>
</trigger>
I am trying to create a list of "trigger" objects using a class. Ideally the object would have id, type, and a list of properties attributes as dictionaries of {name : value}. My code so far is:
class triggerList:
def __init__(self, triggerId, triggerType):
self.id = triggerId
self.type = triggerType
self.properties = []
def add_property(self, buildProperty):
self.properties.append(buildProperty)
def getAllTriggers(buildId):
url = path + 'buildTypes/id:' + buildId + '/triggers'
r = requests.get(url, auth=auth)
tree = ElementTree.fromstring(r.content)
listOfTriggers = []
for trigger in tree.iter('trigger'):
triggerType = trigger.get('type')
triggerId = trigger.get('id')
triggerName = str(triggerId)
triggerName = triggerList(triggerId, triggerType)
listOfTriggers.append(triggerName)
for triggerProperty in tree.iter('property'):
propertyName = triggerProperty.get('name')
propertyValue = triggerProperty.get('value')
propDict = {propertyName : propertyValue}
triggerName.add_property(propDict)
This gives me a list of objects but every object has a list of every property dictionary. This is the output:
a = listOfTriggers[1]
print a.id, a.type, a.properties
>>> TRIGGER_1241 buildDependencyTrigger [{'afterSuccessfulBuildOnly': 'true'}, {'dependsOn': 'bt191'}, {'afterSuccessfulBuildOnly': 'true'}, {'dependsOn': 'bt171'}, {'afterSuccessfulBuildOnly': 'true'}, {'dependsOn': 'bt167'}, {'afterSuccessfulBuildOnly': 'true'}, {'dependsOn': 'bt164'}, {'afterSuccessfulBuildOnly': 'true'}, {'dependsOn': 'bt364'}, {'afterSuccessfulBuildOnly': 'true'}, {'dependsOn': 'Components_Ratchetdb'}, {'afterSuccessfulBuildOnly': 'true'}, {'dependsOn': 'Components_Filedb'}, {'afterSuccessfulBuildOnly': 'true'}, {'dependsOn': 'bt168'}, {'afterSuccessfulBuildOnly': 'true'}, {'dependsOn': 'Components_Tbldb'}, {'quietPeriod': '60'}, {'quietPeriodMode': 'USE_DEFAULT'}, {'triggerRules': '-:version.properties\n-:comment=^Incremented:**\n-:**/*-schema.sql'}]
I don't know how to stop the loop for just the properties for a specific trigger. Is there a way to use ElementTree to only get the properties for a specific trigger? Is there a more efficient way to create this object?
Not directly answering the question, but you may be reinventing the wheel here, check lxml.objectify package:
The main idea is to hide the usage of XML behind normal Python
objects, sometimes referred to as data-binding. It allows you to use
XML as if you were dealing with a normal Python object hierarchy.
Accessing the children of an XML element deploys object attribute
access. If there are multiple children with the same name, slicing and
indexing can be used. Python data types are extracted from XML content
automatically and made available to the normal Python operators.
Simple syntax mistake:
for triggerProperty in trigger.iter('property'):
propertyName = triggerProperty.get('name')
propertyValue = triggerProperty.get('value')
propDict = {propertyName : propertyValue}
triggerName.add_property(propDict)
I was iterating over the whole tree, rather than the triggers. Should be:
for triggerProperty in trigger.iter('property'):
Related
I'm working with XMLs and I'm trying to delete <node> based on element's criteria. The idea is to delete 2nd ITEM. I tried to make list of ITEMS and then based on that list removed them from root lvl but I got
ValueError "ValueError: list.remove(x): x not in list"
and I have no idea how to get to higher lvl.
Code:
import xml.etree.ElementTree as ET
tree = ET.parse("PW.xml")
root = tree.getroot()
items = root.findall('.//ITEM[PROPERTY]')
m = -1
delate = []
for i in items:
pl = i.findall('PROPERTY[#NAME="ID detalu"]')
#print([(pv.attrib['NAME'], pv.text) for pv in pl])
m = m + 1
for p in pl:
if (p.text.startswith('SHP')):
delate.append(m)
tree.write('PW.xml')
XML:
<DATA>
<OBJECT TYPE="Dane">
<ITEM>
<PROPERTY NAME="[1]" />
<PROPERTY NAME="child2">0\557</PROPERTY>
<PROPERTY NAME="child3">MNO001366</PROPERTY>
<PROPERTY NAME="child4">1507</PROPERTY>
<PROPERTY NAME="child5" />
<PROPERTY NAME="child6" />
<PROPERTY NAME="ID detalu">PL.10.000033</PROPERTY>
</ITEM>
<ITEM>
<PROPERTY NAME="[1]" />
<PROPERTY NAME="child2">0\557</PROPERTY>
<PROPERTY NAME="child3">MNO001485</PROPERTY>
<PROPERTY NAME="child4">1626</PROPERTY>
<PROPERTY NAME="child5" />
<PROPERTY NAME="child6">Pintos</PROPERTY>
<PROPERTY NAME="ID detalu">SHP001432</PROPERTY>
</ITEM>
</OBJECT>
</DATA>
I cannot reproduce the error message. Anyway, to remove an element, you need to have a reference to its parent, so that you can do parent.remove(child). The parent of the ITEM elements is OBJECT.
Here is a demo:
import xml.etree.ElementTree as ET
tree = ET.parse("PW.xml")
root = tree.getroot()
to_delete = []
object = root.find("OBJECT")
items = root.findall(".//ITEM")
# Find the items to delete and add them to the to_delete list
for item in items:
prop = item.find("PROPERTY[#NAME='ID detalu']")
if prop is not None and prop.text.startswith("SHP"):
to_delete.append(item)
# Do the actual deletion of items
for item in to_delete:
object.remove(item)
print(ET.tostring(root).decode())
Output:
<DATA>
<OBJECT TYPE="Dane">
<ITEM>
<PROPERTY NAME="[1]" />
<PROPERTY NAME="child2">0\557</PROPERTY>
<PROPERTY NAME="child3">MNO001366</PROPERTY>
<PROPERTY NAME="child4">1507</PROPERTY>
<PROPERTY NAME="child5" />
<PROPERTY NAME="child6" />
<PROPERTY NAME="ID detalu">PL.10.000033</PROPERTY>
</ITEM>
</OBJECT>
</DATA>
I use BS4 to parser .xml,i want to get resattribute number,but get none
how to do it ?
source xml
`<digitizer id="1" integrated="true" csrmusttouch="falsehardprox="true"
physidcsrs="false" pnpid="49154" kind="MULTI_TOUCH" maxcsrs="10">
<monitor left="0" top="0" right="1920" bottom="1080" />`
<properties>
<property name="x" logmin="0" logmax="16383" res="621.7457275" unit="cm" hidusage="0x00010030" guid="{598A6A8F-52C0-4BA0-93AF-AF357411A561}" />
<property name="y" logmin="0" logmax="16383" res="983.9639893" unit="cm" hidusage="0x00010031" guid="{B53F9F75-04E0-4498-A7EE-C30DBB5A9011}" />
<property name="status" logmin="0" logmax="15" res="0" unit="DEFAULT" hidusage="0x000d0042, 0x000d003c, 0x000d0044" guid="{6E0E07BF-AFE7-4CF7-87D1-AF6446208418}" />
<property name="time" logmin="0" logmax="2147483647" res="1" unit="DEFAULT" guid="{436510C5-FED3-45D1-8B76-71D3EA7A829D}" />
<property name="contactid" logmin="0" logmax="31" res="1.861861944" unit="cm" hidusage="0x000d0051" guid="{02585B91-049B-4750-9615-DF8948AB3C9C}" />`
Python Code
a = data_xml.find('digitizer',id="1")
b = a.find('properties')
print(b.get('res'))
Result
None
I have taken your data as html
html="""<digitizer id="1" integrated="true" csrmusttouch="falsehardprox="true"
physidcsrs="false" pnpid="49154" kind="MULTI_TOUCH" maxcsrs="10">
<monitor left="0" top="0" right="1920" bottom="1080" />`
<properties>
<property name="x" logmin="0" logmax="16383" res="621.7457275" unit="cm" hidusage="0x00010030" guid="{598A6A8F-52C0-4BA0-93AF-AF357411A561}" />
<property name="y" logmin="0" logmax="16383" res="983.9639893" unit="cm" hidusage="0x00010031" guid="{B53F9F75-04E0-4498-A7EE-C30DBB5A9011}" />
<property name="status" logmin="0" logmax="15" res="0" unit="DEFAULT" hidusage="0x000d0042, 0x000d003c, 0x000d0044" guid="{6E0E07BF-AFE7-4CF7-87D1-AF6446208418}" />
<property name="time" logmin="0" logmax="2147483647" res="1" unit="DEFAULT" guid="{436510C5-FED3-45D1-8B76-71D3EA7A829D}" />
<property name="contactid" logmin="0" logmax="31" res="1.861861944" unit="cm" hidusage="0x000d0051" guid="{02585B91-049B-4750-9615-DF8948AB3C9C}" />"""
from bs4 import BeautifulSoup
soup=BeautifulSoup(html,"html.parser")
Code::
You can find all property tag and then find res value associate to it!
a = soup.find('digitizer',attrs={"id":"1"})
properties=a.find_all("property")
res_lst=[i['res'] for i in properties]
Output::
['621.7457275', '983.9639893', '0', '1', '1.861861944']
Your xml seems poorly formatted, after reformatting it:
<digitizer id="1" integrated="true" csrmusttouch="" falsehardprox="true" physidcsrs="false" pnpid="49154" kind="MULTI_TOUCH" maxcsrs="10">
<monitor left="0" top="0" right="1920" bottom="1080"/>
<properties>
<property name="x" logmin="0" logmax="16383" res="621.7457275" unit="cm" hidusage="0x00010030" guid="{598A6A8F-52C0-4BA0-93AF-AF357411A561}" />
<property name="y" logmin="0" logmax="16383" res="983.9639893" unit="cm" hidusage="0x00010031" guid="{B53F9F75-04E0-4498-A7EE-C30DBB5A9011}" />
<property name="status" logmin="0" logmax="15" res="0" unit="DEFAULT" hidusage="0x000d0042, 0x000d003c, 0x000d0044" guid="{6E0E07BF-AFE7-4CF7-87D1-AF6446208418}" />
<property name="time" logmin="0" logmax="2147483647" res="1" unit="DEFAULT" guid="{436510C5-FED3-45D1-8B76-71D3EA7A829D}" />
<property name="contactid" logmin="0" logmax="31" res="1.861861944" unit="cm" hidusage="0x000d0051" guid="{02585B91-049B-4750-9615-DF8948AB3C9C}" />
You can easily parse it like this:
from bs4 import BeautifulSoup
with open('data.xml') as raw_resuls:
results = BeautifulSoup(raw_resuls, 'lxml')
for element in results.find_all("properties"):
for property_tag in element.find_all("property"):
print(property_tag['res'])
Output:
621.7457275
983.9639893
0
1
1.861861944
You can find more info about parsing attribute values from xml in the tutorial where the code is from.
Edit: Note that I slightly modified the code to fit your question.
I have two Gtk.Comboboxes on a main window :
the first, has its own Gtk.Liststore
the second one, linked to a Gtk.TreeModelFilter which is linked to a second Gtk.Liststore
When I select a value in the first one, the second one displays values according to my selection. This works well in the main window.
But in my application, I need to use this comboboxes combination many times, and when I use it on another window, this generates a Gtk Error that I don't understand:
"Gtk-CRITICAL **: 00:27:38.289:
gtk_tree_model_filter_set_visible_func: assertion
'filter->priv->visible_method_set == FALSE' failed"
Could someone explain me what's wrong with my code and what is the meaning of that error message?
Here is the glade file (test.ui)
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.22.1 -->
<interface>
<requires lib="gtk+" version="3.20"/>
<object class="GtkListStore" id="liststore1">
<columns>
<!-- column-name id -->
<column type="gchararray"/>
<!-- column-name name -->
<column type="gchararray"/>
</columns>
<data>
<row>
<col id="0" translatable="yes">1</col>
<col id="1" translatable="yes">fruits</col>
</row>
<row>
<col id="0" translatable="yes">2</col>
<col id="1" translatable="yes">colors</col>
</row>
</data>
</object>
<object class="GtkListStore" id="liststore2">
<columns>
<!-- column-name id -->
<column type="gchararray"/>
<!-- column-name name -->
<column type="gchararray"/>
</columns>
<data>
<row>
<col id="0" translatable="yes">10</col>
<col id="1" translatable="yes">lemon</col>
</row>
<row>
<col id="0" translatable="yes">11</col>
<col id="1" translatable="yes">apple</col>
</row>
<row>
<col id="0" translatable="yes">12</col>
<col id="1" translatable="yes">strawberry</col>
</row>
<row>
<col id="0" translatable="yes">20</col>
<col id="1" translatable="yes">blue</col>
</row>
<row>
<col id="0" translatable="yes">21</col>
<col id="1" translatable="yes">yellow</col>
</row>
<row>
<col id="0" translatable="yes">22</col>
<col id="1" translatable="yes">purple</col>
</row>
</data>
</object>
<object class="GtkTreeModelFilter" id="filter">
<property name="child_model">liststore2</property>
</object>
<object class="GtkWindow" id="window1">
<property name="can_focus">False</property>
<signal name="destroy" handler="on_quit" swapped="no"/>
<child>
<placeholder/>
</child>
<child>
<object class="GtkBox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<property name="spacing">20</property>
<child>
<object class="GtkToolbar">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkToolButton">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Open other</property>
<property name="use_underline">True</property>
<signal name="clicked" handler="on_other" swapped="no"/>
</object>
<packing>
<property name="expand">False</property>
<property name="homogeneous">True</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkGrid">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="margin_left">20</property>
<property name="margin_right">20</property>
<property name="row_spacing">5</property>
<property name="column_spacing">10</property>
<property name="column_homogeneous">True</property>
<child>
<object class="GtkComboBox" id="w1_combo1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">liststore1</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkComboBox" id="w1_combo2">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">filter</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo1</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">0</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo2</property>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</object>
</child>
</object>
<object class="GtkDialog" id="window2">
<property name="can_focus">False</property>
<property name="type_hint">dialog</property>
<property name="transient_for">window1</property>
<child>
<placeholder/>
</child>
<child internal-child="vbox">
<object class="GtkBox">
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<property name="spacing">2</property>
<child internal-child="action_area">
<object class="GtkButtonBox">
<property name="can_focus">False</property>
<property name="layout_style">end</property>
<child>
<object class="GtkButton" id="btn_close">
<property name="label" translatable="yes">Close</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkBox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="valign">center</property>
<property name="margin_left">20</property>
<property name="margin_right">20</property>
<property name="margin_top">20</property>
<property name="margin_bottom">20</property>
<property name="vexpand">True</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkGrid">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="valign">center</property>
<property name="margin_top">20</property>
<property name="margin_bottom">20</property>
<property name="vexpand">True</property>
<property name="row_spacing">5</property>
<property name="column_spacing">10</property>
<property name="column_homogeneous">True</property>
<child>
<object class="GtkComboBox" id="w2_combo1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">liststore1</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkComboBox" id="w2_combo2">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">filter</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo1</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">0</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo2</property>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</object>
</child>
<action-widgets>
<action-widget response="-7">btn_close</action-widget>
</action-widgets>
</object>
</interface>
and the python file (test.py):
#!/usr/bin/env python3
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
import sys
class Main:
def __init__(self):
self.builder = Gtk.Builder()
self.builder.add_from_file('test.ui')
self.builder.connect_signals(self)
self.obj = self.builder.get_object
self.window = self.obj('window1')
self.combo1 = self.obj('w1_combo1')
self.combo2 = self.obj('w1_combo2')
self.combo1.connect('changed', self.on_select, self.combo2)
self.filter = self.obj('filter')
self.filter.set_visible_func(self.filter_func)
self.combo1_val = None
self.window.show()
def on_other(self, btn):
Other(self.obj)
def on_select(self, combo, next_combo):
self.combo1_val = combo.get_active_id()
self.filter.refilter()
next_combo.set_active(0)
def filter_func(self, model, iter, data):
if self.combo1_val is None: return True
else: return self.combo1_val == model[iter][0][:1]
def on_quit(self, widget):
Gtk.main_quit()
class Other:
def __init__(self, obj):
self.obj = obj
self.window = self.obj('window2')
self.combo1 = self.obj('w2_combo1')
self.combo2 = self.obj('w2_combo2')
self.combo1.connect('changed', self.on_select, self.combo2)
self.filter = self.obj('filter')
self.filter.set_visible_func(self.filter_func)
self.btn_close = self.obj('btn_close')
self.btn_close.connect('clicked', self.on_hide)
self.combo1_val = None
self.window.show()
def on_select(self, combo, next_combo):
self.combo1_val = combo.get_active_id()
self.filter.refilter()
next_combo.set_active(0)
def filter_func(self, model, iter, data):
if self.combo1_val is None: return True
else: return self.combo1_val == model[iter][0][:1]
self.window.show()
def on_hide(self, btn):
self.window.hide()
def main():
app = Main()
Gtk.main()
if __name__ == "__main__":
sys.exit(main())
Thank you in advance.
The problem was due to the fact that the second combobox on the main window and the second combobox on 'other' window were using the same filter.
I've created another filter and the second comboboxes have now their own filter linked to a common Gtk.Liststore.
Everything works fine, now.
Here are the corrected files :
The glade one :
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.22.1 -->
<interface>
<requires lib="gtk+" version="3.20"/>
<object class="GtkListStore" id="liststore1">
<columns>
<!-- column-name id -->
<column type="gchararray"/>
<!-- column-name name -->
<column type="gchararray"/>
</columns>
<data>
<row>
<col id="0" translatable="yes">1</col>
<col id="1" translatable="yes">fruits</col>
</row>
<row>
<col id="0" translatable="yes">2</col>
<col id="1" translatable="yes">colors</col>
</row>
</data>
</object>
<object class="GtkListStore" id="liststore2">
<columns>
<!-- column-name id -->
<column type="gchararray"/>
<!-- column-name name -->
<column type="gchararray"/>
</columns>
<data>
<row>
<col id="0" translatable="yes">10</col>
<col id="1" translatable="yes">lemon</col>
</row>
<row>
<col id="0" translatable="yes">11</col>
<col id="1" translatable="yes">apple</col>
</row>
<row>
<col id="0" translatable="yes">12</col>
<col id="1" translatable="yes">strawberry</col>
</row>
<row>
<col id="0" translatable="yes">20</col>
<col id="1" translatable="yes">blue</col>
</row>
<row>
<col id="0" translatable="yes">21</col>
<col id="1" translatable="yes">yellow</col>
</row>
<row>
<col id="0" translatable="yes">22</col>
<col id="1" translatable="yes">purple</col>
</row>
</data>
</object>
<object class="GtkTreeModelFilter" id="w1_filter">
<property name="child_model">liststore2</property>
</object>
<object class="GtkWindow" id="window1">
<property name="can_focus">False</property>
<signal name="destroy" handler="on_quit" swapped="no"/>
<child>
<placeholder/>
</child>
<child>
<object class="GtkBox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<property name="spacing">20</property>
<child>
<object class="GtkToolbar">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkToolButton">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Open other</property>
<property name="use_underline">True</property>
<signal name="clicked" handler="on_other" swapped="no"/>
</object>
<packing>
<property name="expand">False</property>
<property name="homogeneous">True</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkGrid">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="margin_left">20</property>
<property name="margin_right">20</property>
<property name="row_spacing">5</property>
<property name="column_spacing">10</property>
<property name="column_homogeneous">True</property>
<child>
<object class="GtkComboBox" id="w1_combo1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">liststore1</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkComboBox" id="w1_combo2">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">w1_filter</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo1</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">0</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo2</property>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</object>
</child>
</object>
<object class="GtkTreeModelFilter" id="w2_filter">
<property name="child_model">liststore2</property>
</object>
<object class="GtkDialog" id="window2">
<property name="can_focus">False</property>
<property name="type_hint">dialog</property>
<property name="transient_for">window1</property>
<child>
<placeholder/>
</child>
<child internal-child="vbox">
<object class="GtkBox">
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<property name="spacing">2</property>
<child internal-child="action_area">
<object class="GtkButtonBox">
<property name="can_focus">False</property>
<property name="layout_style">end</property>
<child>
<object class="GtkButton" id="btn_close">
<property name="label" translatable="yes">Close</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">False</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkBox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="valign">center</property>
<property name="margin_left">20</property>
<property name="margin_right">20</property>
<property name="margin_top">20</property>
<property name="margin_bottom">20</property>
<property name="vexpand">True</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkGrid">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="valign">center</property>
<property name="margin_top">20</property>
<property name="margin_bottom">20</property>
<property name="vexpand">True</property>
<property name="row_spacing">5</property>
<property name="column_spacing">10</property>
<property name="column_homogeneous">True</property>
<child>
<object class="GtkComboBox" id="w2_combo1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">liststore1</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkComboBox" id="w2_combo2">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="model">w2_filter</property>
<property name="active">0</property>
<property name="id_column">0</property>
<property name="active_id">0</property>
<child>
<object class="GtkCellRendererText"/>
<attributes>
<attribute name="text">1</attribute>
</attributes>
</child>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">1</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo1</property>
</object>
<packing>
<property name="left_attach">0</property>
<property name="top_attach">0</property>
</packing>
</child>
<child>
<object class="GtkLabel">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Combo2</property>
</object>
<packing>
<property name="left_attach">1</property>
<property name="top_attach">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
</object>
</child>
<action-widgets>
<action-widget response="-7">btn_close</action-widget>
</action-widgets>
</object>
</interface>
And the python one :
#!/usr/bin/env python3
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
import sys
class Main:
def __init__(self):
self.builder = Gtk.Builder()
self.builder.add_from_file('test.ui')
self.builder.connect_signals(self)
self.obj = self.builder.get_object
self.window = self.obj('window1')
self.combo1 = self.obj('w1_combo1')
self.combo2 = self.obj('w1_combo2')
self.combo1.connect('changed', self.on_select, self.combo2)
self.filter = self.obj('w1_filter')
self.filter.set_visible_func(self.filter_func)
self.combo1_val = None
self.window.show()
def on_other(self, btn):
Other(self.obj)
def on_select(self, combo, next_combo):
self.combo1_val = combo.get_active_id()
self.filter.refilter()
next_combo.set_active(0)
def filter_func(self, model, iter, data):
#print(self.combo1_val, model[iter][0][:1])
if self.combo1_val is None: return True
else: return self.combo1_val == model[iter][0][:1]
def on_quit(self, widget):
Gtk.main_quit()
class Other:
def __init__(self, obj):
self.obj = obj
self.window = self.obj('window2')
self.combo1 = self.obj('w2_combo1')
self.combo2 = self.obj('w2_combo2')
self.combo1.connect('changed', self.on_select, self.combo2)
self.filter = self.obj('w2_filter')
self.filter.set_visible_func(self.filter_func)
self.btn_close = self.obj('btn_close')
self.btn_close.connect('clicked', self.on_hide)
self.combo1_val = None
self.window.show()
def on_select(self, combo, next_combo):
self.combo1_val = combo.get_active_id()
self.filter.refilter()
next_combo.set_active(0)
def filter_func(self, model, iter, data):
#print(self.combo1_val, model[iter][0][:1])
if self.combo1_val is None: return True
else: return self.combo1_val == model[iter][0][:1]
self.window.show()
def on_hide(self, btn):
self.window.hide()
def main():
app = Main()
Gtk.main()
if __name__ == "__main__":
sys.exit(main())
I am triying to get the String "W:_fdsw\Projects\HIL\releases\release_9_1_0\Config\CDNG\UX_EF_TSHIL\UX_EF_TSHIL.CDP" and save it in a variable using minidom
<TOOL id="CONTROLDESKNG" xsi:type="tool">
<TOOL-HOST xsi:type="unicode">tsp:QMUC633107:5018</TOOL-HOST>
<TOOL-NAME xsi:type="unicode">CONTROLDESKNG</TOOL-NAME>
<START-OPTION xsi:type="integer">0</START-OPTION>
<START-PRIORITY xsi:type="integer">0</START-PRIORITY>
<SETTINGS xsi:type="dynamicPropertySet">
<PROPERTY format-rev="1" name="ExpName" propertyType="string" readonly="false" xsi:type="_property">
<VALUE xsi:type="unicode">K53MU</VALUE>
</PROPERTY>
<PROPERTY format-rev="1" name="ModelDir" propertyType="uri" readonly="false" xsi:type="_property">
<VALUE xsi:type="unicode">W:\_fdsw\Projects\HIL\releases\release_9_1_0\Config\CDNG\UX_EF_TSHIL\Variable Descriptions\UX_EF_TSHIL.sdf(#14)</VALUE>
</PROPERTY>
<PROPERTY format-rev="1" name="PrjFile" propertyType="uri" readonly="false" xsi:type="_property">
<VALUE xsi:type="unicode">W:\_fdsw\Projects\HIL\releases\release_9_1_0\Config\CDNG\UX_EF_TSHIL\UX_EF_TSHIL.CDP</VALUE>
</PROPERTY>
<PROPERTY format-rev="1" name="RecordingFormat" propertyType="string" readonly="false" xsi:type="_property">
<VALUE xsi:type="unicode">MDF</VALUE>
</PROPERTY>
<PROPERTY format-rev="1" name="ToolState" propertyType="string" readonly="false" xsi:type="_property">
<VALUE xsi:type="unicode">Online</VALUE>
</PROPERTY>
<PROPERTY format-rev="1" name="VersionCDNG" propertyType="string" readonly="false" xsi:type="_property">
<VALUE xsi:type="unicode">5.5</VALUE>
</PROPERTY>
<PROPERTY format-rev="1" name="VersionHILAPI" propertyType="string" readonly="false" xsi:type="_property">
<VALUE xsi:type="unicode">2015-B</VALUE>
</PROPERTY>
</SETTINGS>
</TOOL>
My code is:
xmldoc = minidom.parse('C:\Users\qxn5622\Desktop\EF10018\DEFAULT.tbc')
propertyList = xmldoc.getElementsByTagName('PROPERTY')
for prop in propertyList:
if prop.attributes["name"].value == "ModelDir":
myString = prop.getElementsByTagName("VALUE").value
I think the problem is that the element I am trying to get doesnt have any Id.
Can anybody help me?
This might help
from xml.dom.minidom import parse
dom = parse('C:\Users\qxn5622\Desktop\EF10018\DEFAULT.tbc')
propertyList = dom.getElementsByTagName('PROPERTY')
for prop in propertyList:
if prop.getAttribute('name') == "PrjFile":
myString = prop.getElementsByTagName("VALUE")
print myString[0].firstChild.nodeValue
Output:
W:\_fdsw\Projects\HIL\releases\release_9_1_0\Config\CDNG\UX_EF_TSHIL\UX_EF_TSHIL.CDP
I'm trying to setup a little download application using Glade, PyGTK, and Python. I have it planned how I'd like to script this progress bar and all, though I feel I'm going about it the wrong way as... Well... It's not working.
I'm using a little script I found for a checking the percentage of a download and then usually it would print to terminal, but instead I'd like it alter a label in Glade. Though, instead of the label changing when as the download progresses, the GUI freezes until the file is done and THEN updates saying it's 100% complete.
What would be the best method about making something like this work? Any help is appreciated, thanks in advance!
Python Script:
import sys
import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade
import urllib2
import time
class FileSelector:
def __init__(self):
#Set the Glade file
filename = "FileSelector.glade"
self.builder = gtk.Builder()
self.builder.add_from_file(filename)
self.builder.connect_signals(self)
self.window = self.builder.get_object("MainWindow")
self.label1 = self.builder.get_object("label1")
def on_MainWindow_destroy(self, obj):
gtk.main_quit() #make the program quit
def btnSubmit_clicked(self, widget):
status_dropbox = self.builder.get_object("chkboxDropbox")
status_python = self.builder.get_object("chkboxPython")
status_chrome = self.builder.get_object("chkboxChrome")
#Start downloader script
url = "http://dl.dropbox.com/u/9235267/project.png"
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
self.label1.set_text(status)
f.close()
if __name__ == "__main__":
FileSelector()
gtk.main()
Glade File (FileSelector.glade):
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<requires lib="gtk+" version="2.24"/>
<!-- interface-naming-policy project-wide -->
<object class="GtkWindow" id="MainWindow">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="title" translatable="yes">MainWindow</property>
<property name="resizable">False</property>
<property name="window_position">center</property>
<signal name="destroy" handler="on_MainWindow_destroy" swapped="no"/>
<child>
<object class="GtkVBox" id="vbox1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkLabel" id="label1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="label" translatable="yes">Enviroment Downloader</property>
<attributes>
<attribute name="style" value="normal"/>
<attribute name="size" value="300"/>
</attributes>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<object class="GtkCheckButton" id="chkboxDropbox">
<property name="label" translatable="yes">Dropbox</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="use_action_appearance">False</property>
<property name="draw_indicator">True</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">1</property>
</packing>
</child>
<child>
<object class="GtkCheckButton" id="chkboxPython">
<property name="label" translatable="yes">Python</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="use_action_appearance">False</property>
<property name="draw_indicator">True</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">2</property>
</packing>
</child>
<child>
<object class="GtkCheckButton" id="chkboxChrome">
<property name="label" translatable="yes">Google Chrome</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">False</property>
<property name="use_action_appearance">False</property>
<property name="draw_indicator">True</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">3</property>
</packing>
</child>
<child>
<object class="GtkButton" id="btnSubmit">
<property name="label" translatable="yes">Download/Run</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="use_action_appearance">False</property>
<signal name="clicked" handler="btnSubmit_clicked" swapped="no"/>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">4</property>
</packing>
</child>
</object>
</child>
</object>
</interface>
After the line
self.label1.set_text(status)
Add:
while gtk.events_pending():
gtk.main_iteration()
This will update the GUI and run the main loop while you are waiting for the file to download, and you won't have to use threads.
You will need to use threads for this. If you are downloading in the callback function then the eventing is blocked on the button & you can see that the button is in pressed state i.e. it is waiting for the callback function to complete and return. Although my knowledge of python is nil, I could cook up some sample as follows using google etc:
import sys
import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade
import urllib2
import time
import threading
import glib
# Replace this with what you want to do
def download(label):
index = 0
while True:
if index>1200:
break
index += 120
time.sleep(1)
status = r"%10d " % (index)
label.set_label(status)
class FileSelector:
def __init__(self):
#Set the Glade file
filename = "FileSelector.glade"
self.builder = gtk.Builder()
self.builder.add_from_file(filename)
self.builder.connect_signals(self)
self.window = self.builder.get_object("MainWindow")
self.label1 = self.builder.get_object("label1")
def on_MainWindow_destroy(self, obj):
gtk.main_quit() #make the program quit
def btnSubmit_clicked(self, widget):
status_dropbox = self.builder.get_object("chkboxDropbox")
status_python = self.builder.get_object("chkboxPython")
status_chrome = self.builder.get_object("chkboxChrome")
# Launch the thread to update label
threading.Thread(target=download, args=(self.builder.get_object("label1"),)).start()
if __name__ == "__main__":
FileSelector()
glib.threads_init()
# Add gdk thread enter and leave
gtk.main()
You can refer this question as well.
Hope this helps!
PS: Add thread safety & maybe disable button till download is complete?