Microsoft Dynamics Ax developer's blog

Tuesday, February 06, 2007

Python

Every programmer, ecpecialy one, which deals with some ugly language like X++ or BAAN 4GL should know some scripting language. Its a kind of practical and easy tool which allows you to write small programs quickly, in cost of performance.

My favorite is Python. It is nice, mature enough and widely supported (even my Pocket PC has an interpretter).

For example one task which I did with python a couple days ago is a preparation of data of the legacy system to load in Dynamics Ax. The source file consists of text lines, where data fields are separated with the piplene character ('|'). Some of data fields values contain pipeline character too. The first field of the line identifies type of the data (invenotory group or inventory item). The file was encoded using DOS (cp866) encoding. So there was 3 actions po perform:

  • recode data to Windows encoding (cp1251)
  • separate item data from inventory group data
  • check for lines which pipeline in data


It was done by the following scipts:

1. Splitting files by data type and converting from DOS to Windows

src=open('input.txt', 'r')
dst = {'asl': open('inventory.txt', 'w'), 'ctl': open('group.txt', 'w')}
lineNo = 1
for line in src:
type = line.split('|')[0]
if type in dst:
try:
dst[type].write(line.decode('cp866').encode('cp1251'))
except:
print line
print lineNo
lineNo += 1


2. Checking for correctnes:

import sys
lineCount = 8
fileName = sys.argv[1] if len(sys.argv)>1 else 'inventory.txt'
for lineNo, line in enumerate(open(fileName, 'r')):
if line.count('|')!=lineCount:
print lineNo
print line.decode('cp1251').encode('cp866')


As you can see it is readable and easy.

If you get interested, look at the following links:

No comments: