Writing by shivdev on Saturday, 8 of November , 2014 at 10:05 pm
I was running into several errors while accessing a dictionary persisted in MongoDB as JSON (with Unicode) until I found this post on stackoverflow.com.
TypeError: string indices must be integers, not unicode
So basically the way to workaround the problem is as follows:
import json, ast
# You would assume this would work ...
somekey_val = dict[SOME_KEY]
# but due to frustrations with unicode in python handle it
try:
somekey_val = ast.literal_eval(dict[SOME_KEY])
except Exception, e:
print 'unicode conversion not needed for some_key'
# do regular processing from here on
process( somekey_val )
Category: Python
Writing by shivdev on Monday, 3 of November , 2014 at 6:18 pm
This post from stackoverflow.com explains it.
Basically, you will need to use the default=json_util.default argument as defined in the PyMongo Docs
So, while converting a date object in a dictionary to JSON
from bson import json_util
import json
json_str = json.dumps(anObject, default=json_util.default)
print json_str
And while reading back the JSON string into a dictionary
from bson import json_util
import json
json.loads(json_str, object_hook=json_util.object_hook)
Category: Python
Writing by shivdev on Thursday, 9 of October , 2014 at 5:54 pm
If you’re trying to use the –exec option and need to pass in arguments, then you would need to use — to let –exec know that these are arguments to the script that needs to be executed.
# No arguments passed to test.py
exec start-stop-daemon –start –exec python test.py
# Arguments (-i $PARAM) passed to test.py
exec start-stop-daemon –start –exec python test.py — -i $PARAM
Category: Linux,Python
Writing by shivdev on Wednesday, 1 of October , 2014 at 3:52 am
We have a bunch of Python (2.7) virtual environments and I needed a way to figure out a way to list modules installed by pip within the context of that venv and then grep for a particular one. I’m not a super Python expert at this time, but wrote up a small script to list this.
Here’s a python script:
# pip_installed_modules.py
import pip
def main():
modules = pip.get_installed_distributions()
for m in modules:
print m
if __name__ == "__main__":
main()
Here’s my alias:
alias pipmodules=’python ~/bin/pip_installed_modules.py’
Now I can simply grep for specific modules or just see the installed modules.
Category: Python