Recent Python Tips and Gotchas

A grab bag of small issues I ran into recently.

Preserve OrderedDict when dumping/loading JSON

json.dumps() keeps the order of OrderedDict. While loading, pass object_pairs_hook=collections.OrderedDict to coerce objects into ordered dictionaries.

Install a specific package version with pip

pip install lxml==3.4.4

Download without installing:

pip download lxml

Open view-source in Chrome with Selenium

Download Chromedriver: https://sites.google.com/a/chromium.org/chromedriver/downloads

1
2
3
4
from selenium import webdriver

driver = webdriver.Chrome(chromedriver_path)
driver.get('view-source:http://www.baidu.com')

WebDriverException: Message: chrome not reachable

Call webdriver.quit() to clean up the session.

Sending raw strings with requests.post

requests.post(data=...) accepts dicts or strings. When you pass a string, Requests sends it as-is and will not set Content-Type: application/x-www-form-urlencoded. Add the header yourself. Passing a dict adds the header automatically and URL-encodes the payload.

Dynamically add and rename PyQt widgets

1
2
3
4
5
6
7
8
9
10
def add_button_click(self):
new_label = QtGui.QLabel()
new_lineedit = QtGui.QLineEdit()
self.add_num += 1
new_label.setText(str(self.add_num))
new_lineedit.setMinimumSize(500, 20)
new_lineedit.setObjectName('lineEdit_%s' % self.add_num)
self.verticalLayout.addWidget(new_label)
self.verticalLayout_2.addWidget(new_lineedit)
self.added_lineedit.append(new_lineedit)