30 Apr 2009

Python Tips - python流程图生成

中文ubuntu论坛python社区anticlockwise的文章(原文)
转载请注明版权.

This is a python flow chart drawing implementation.





#!/usr/bin/env python
# -*- coding: utf-8 -*-

# flow_parser.py
# author: Rongzhou Shen
# date: 2009-02-11

from pyparsing import *

# PYPARSING DEFINITION =========================
LSQUARE, RSQUARE, SEMI, ASSIGN, QUOTE = map(Suppress, '[];="')
LBRACE, RBRACE, AT, LBRACK, RBRACK = map(Suppress, '{}@()')

# Definition part of the flow_def file
node_id = Word(alphanums + "_")("id")
node_type = Word(alphas)("type")
declaration = node_type + LSQUARE + node_id + RSQUARE
value = QuotedString('"')
definition = Group(declaration("declaration") + ASSIGN + value("value") + SEMI)

# Flow part of the flow_def file
flow = Group(node_id + OneOrMore(Group('=>' + node_id)) + SEMI)

# Grammar definition of the whole file
flow_impl = OneOrMore(definition)("definitions") + OneOrMore(flow)("flows")
flow_def = AT + LBRACK + QuotedString('"')("flow_name") + RBRACK + LBRACE +\
flow_impl("flow_impl") + RBRACE
# END PYPARSING DEFINITION ==============================

#sample = """
#@("A test flow_chart") {
#    process[node1] = "This is a test process";
#    process[node2] = "This is another test process";
#    a => b => c;
#    ffew => fweji;
#}"""

def test_parse():
expected = ['process', '[', 'node1', ']', '=', '"',
'This is a test process', '"', ';']
test_def = 'process[node1] = "This is a test process";'
data = definition.parseString(test_def)
assert len(data) == len(expected)
assert all([x == y for x, y in zip(expected, data)])

expected = ['a', '=>', 'b', '=>', 'c', ';']
test_flow = 'a => b => c;'
data = flow.parseString(test_flow)
assert len(data) == len(expected)
assert all([x == y for x, y in zip(expected, data)])


用法如下:

Usage:

@("This is a test graph") {
process[p1] = "This is a test process";
process[p2] = "This is another process";
condition[c1] = "This is a condition";

p1 => p2;
c1 => p1;
c1 => p2;
}


结果如下:

The flow chart generated is:


No comments :

Post a Comment