Just somewhere to keep my notes while I'm playing.

Thursday, January 16, 2020

Compiling Python

Python is great in that you can extend the language using pip to download libraries, but if you want to run your code on a number of servers, you have to ensure that they all have the required libraries.

One way around this is to compile your code so that it runs native.  The example below reads data from a Mongo database and prints it in a pretty format.

jinkersont@testdockerhost:~/python$ cat Mongo.py
import pymongo
import pprint

from pymongo import MongoClient
muser = "dba"
mpassword = "haha"
mhost = "mongodb1.hehe.hoho"
mport = 27017
uri = "mongodb://%s:%s@%s:%s" % ( muser, mpassword, mhost, mport )
client = MongoClient(uri)
db = client['evergreen']
print db.list_collection_names()
collection = db['customers']
pprint.pprint(collection.find_one())
jinkersont@testdockerhost:~/python$

To run this we require the pymongo and pprint libraries to be installed.
apt install python-pip
pip install pymongo pprint
The output looks like this:
jinkersont@testdockerhost:~/python$ python Mongo.py
[u'customers']
{u'_id': ObjectId('5df8ed88d819a6f218b58bc9'),
 u'age': 25.0,
 u'cars': [u'Audi R8'],
 u'name': u'Honey'}
jinkersont@testdockerhost:~/python$

You can compile this code using pyinstaller
pip install pyinstaller
pyinstaller --onefile Mongo.py
Then you can run the code using:

jinkersont@testdockerhost:~/python$ file dist/Mongo
dist/Mongo: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/l, for GNU/Linux 2.6.32, BuildID[sha1]=294d1f19a085a730da19a6c55788ec08c2187039, stripped
jinkersont@testdockerhost:~/python$ dist/Mongo
[u'customers']
{u'_id': ObjectId('5df8ed88d819a6f218b58bc9'),
 u'age': 25.0,
 u'cars': [u'Audi R8'],
 u'name': u'Honey'}
jinkersont@testdockerhost:~/python$





No comments: