Package: pyflowchart
PyFlowchartEnglish |机翻中文PyFlowchart is a Python package that lets you:Write flowcharts in Python.Translate Python source code into flowcharts.PyFlowchart produces flowcharts in theflowchart.jsflowchart DSL, a widely used textual representation of flowcharts. You can convert these flowcharts to images usingflowchart.js.org,francoislaberge/diagrams, or some markdown editors. Alternatively, we  also support an option to output the generated flowchart into a interactive HTML page.Get PyFlowchart$pipinstallpyflowchartQuick StartWant toflowchart your Python code inexample.py?Run this:$python-mpyflowchartexample.py⚠️ PyFlowchart works withPython 3.7+. To check your Python version, runpython --version.If you have both Python 2 and Python 3 installed, you may need to usepython3instead ofpython. This is becoming less common asPython 2 is sunsetting.PyFlowchart will output the generated flowchart.js DSL. You can convert the output code to a rendered diagram by going tohttp://flowchart.js.orgor using editors like Typora.To output a HTML filecontaining the generated flowchart:$python-mpyflowchartexample.py-oexample.html
$# open example.htmlOpenexample.htmlin your browser to see the output in graphical representation.To specify a function (or a method in a class) to flowchartlize:Use the-fflag to specify the function or method name.$python-mpyflowchartexample.py-ffunction_name# or$python-mpyflowchartexample.py-fClassName.method_nameFor example, to flowchartlize theadd()function in theMyClassclass, you would use the following command:python3 -m pyflowchart example.py -f MyClass.add.🎉Now you are ready to flowchart your code!To learn more about how to use PyFlowchart, keep reading this document.Flowchart in PythonPyFlowchart lets you write flowcharts in Python, which can be automatically translated into theflowchart.jsDSL.The followingflowchart.js node typesare supported:StartNodeOperationNodeConditionNodeInputOutputNodeSubroutineNodeEndNodeTo connect nodes, use theconnect()method. For ConditionNodes, use theconnect_{yes|no}syntax. You can optionally specify the connect_direction as a second parameter.Get a Flowchart with your start node and call itsflowchart()method to generate flowchart.js flowchart DSL：frompyflowchartimport*st=StartNode('a_pyflow_test')op=OperationNode('do something')cond=ConditionNode('Yes or No?')io=InputOutputNode(InputOutputNode.OUTPUT,'something...')sub=SubroutineNode('A Subroutine')e=EndNode('a_pyflow_test')st.connect(op)op.connect(cond)cond.connect_yes(io)cond.connect_no(sub)sub.connect(op,"right")# sub->op line starts from the right of subio.connect(e)fc=Flowchart(st)print(fc.flowchart())Output:st0=>start: start a_pyflow_test
op1=>operation: do something
cond2=>condition: Yes or No?
io3=>inputoutput: output: something...
e5=>end: end a_pyflow_test
sub4=>subroutine: A Subroutine

st0->op1
op1->cond2
cond2->
cond2->
cond2(yes)->io3
io3->e5
cond2(no)->sub4
sub4(right)->op1You can visithttp://flowchart.js.organd translate the generated textual representation into SVG flow chart diagrams:(v0.3.0) You can also usepyflowchart.output_htmlto generate a page similar to the picture above:output_html('output.html','a_pyflow_test',fc.flowchart())By the way, many Markdown editors, like Typora, also support this flowchart syntax. For more information, seethe Typora documentation on flowcharts. If you prefer the command line, you can usefrancoislaberge/diagrams.Set Params to NodesStarting with v0.2.0, you can use theNode.set_param(key, value)method to generate flowcharts like this:element(param1=value1,param2=value2)=>start: Start(See alsoadrai/flowchart.js#node-specific-specifiers-by-type)There is also a shortcut to set thealign-next=noparameter for ConditionNodes:cond=ConditionNode("a cond node")cond.no_align_next()# or do this at __init__:cond=ConditionNode("a cond node",align_next=False)This usually works with a connect_direction customization:cond.connect_yes(op,"right")The generated flowchart will look like:cond(align-next=no)=>condition: Yes or No?
...
cond(yes,right)->opPython to FlowchartPyFlowchart can also translate your Python code into flowcharts.For example, let's say you have a Python file calledsimple.pywith the following code:deffoo(a,b):ifa:print("a")else:foriinrange(3):print("b")returna+bTo generate a flowchart from this code, you can run the following command in the terminal:$python-mpyflowchartsimple.py# output flowchart code.Or, in Python:>>>frompyflowchartimportFlowchart>>>withopen('simple.py')asf:...code=f.read()...>>>fc=Flowchart.from_code(code)>>>print(fc.flowchart())# output flowchart code.Advanced UsagesAs mentioned above, we useFlowchart.from_codeto translate Python codes into Flowcharts. Thefrom_codeis defined as:Flowchart.from_code(code,field="",inner=True,simplify=True,conds_align=False)code: The Python code to be converted into a flowchart.field: The name of a field in the code to be converted into a flowchart. If this parameter is not specified, the entire code will be converted.inner: IfTrue, the body of the field will be parsed as a nested flowchart. IfFalse, the body of the field will be parsed as a single node.simplify: IfTrue, simple If and Loop statements will be simplified. For example, an If statement with a single expression will be converted into a single node.conds_align: IfTrue, consecutive If statements will be aligned in the flowchart.PyFlowchart CLI is an interface for this function:python-mpyflowchart[-fFIELD][-i][--no-simplify][--conds-align][-oOUTPUT]code_file-f FIELD: The name of the field to be converted into a flowchart.-i:  If specified, the body of the field will be parsed as a nested flowchart.--no-simplify:  If specified, the If and Loop statements will not be simplified.--conds-align: If specified, consecutive If statements will be aligned in the flowchart.-o OUTPUT: If specified, output the flowchart to specific file with a format indicating by the extension name. (only support*.htmlfor now)⚠️-ois not a part ofFlowchart.from_code. It'sfrom pyflowchar import output_html.fieldthefieldis the path to a field (i.e. a function) you want to draw a flowchart.# example.pyprint("start")deffoo():foo="foo"classBar():defbuzz(self,f):defg(self):print("g")f(self)returng(self)Bar().buzz(foo)print("end")Forexample.pyabove, available paths are:- "" (means the whole code)
- "foo"
- "Bar.buzz"
- "Bar.buzz.g"To generate a flowchart ofBar.buzz.g：# PythonfrompyflowchartimportFlowchartwithopen('example.py')asf:code=f.read()fc=Flowchart.from_code(code,field='Bar.buzz.g',inner=False)print(fc.flowchart())Or:# CLIpython-mpyflowchartexample.py-fBar.buzz.gOutput result:innerTheinnerparameter controls how the parser behaves. Ifinner=True, the parser will look into the field and parse its body. Ifinner=False, the parser will take the field as a single node.In CLI, the-iargument setsinner=True. The absence of-iargument impliesinner=False.🔧 For developers: Techly,inner=Truemeans parsingfield.body, whileinner=Falseparses[field].simplifyThesimplifyparameter controls whether to simplify If and Loop statements. Whensimplify=True, an If or Loop statements with one-line-body will be simplified into a single node.For example, the following code:# example_simplify.pya=1ifa==1:print(a)whilea<4:a=a+1Would be converted into the following flowchart whensimplify=True:flowchart=Flowchart.from_code(example_simplify_py,field="",inner=True)print(flowchart.flowchart())# SH $ python -m pyflowchart example_simplify.pyAnd withsimplify=False:flowchart=Flowchart.from_code(example_simplify_py,field="",inner=True,simplify=False)print(flowchart.flowchart())# SH $ python -m pyflowchart --no-simplify example_simplify.pyconds-align (Beta)Theconds-alignparameter controls whether consecutive If statements are aligned in the flowchart. Whenconds-align=True, consecutive If statements are aligned in the flowchart.# example-conds-align.pyifcond1:op1ifcond2:op2ifcond3:op3op_endNote:This feature is still in beta and may not work perfectly in all cases.output html and imagesYou can also directly ouput the generated flowchart.js DSL into an html by adding the parameter-o output.htmlwhere you specify an output filename ending in.htmlor.htm.Opening theoutput.htmlin your browser will let you visualize the diagrams. You can tweak the code and click run to update the diagram. There are also links to download the current visuals as a.svgor.pngimage.⚠️ The output file specified will overwrite any file that already has that name.🐍 To use this feature via Python instead of CLI, calloutput_html(output_name: str, field_name: str, flowchart: str) -> None:>>>importpyflowchart>>>help(pyflowchart.output_html)Beautify FlowchartsThe flowcharts generated by PyFlowchart may not always be perfect. In these cases, you can modify the generated flowchart code yourself or consider making your Python source code more clear. Clear and beautiful Python source code will result in more beautiful flowcharts generated by PyFlowchart.An example: If you don't like the flowchart flow direction you can tweak a condition by modifying with with directions such as:TODOsDirectly generate flowchart SVG/HTML:$pyflowchartexample.py-oflowchart.svgDepends onnode.jsandflowchart.js.PyFlowchart GUIAGUIfor PyFlowchart would be amazing. You could paste your Python code into it, and the flowchart DSL would be generated in real time, with the flowchart displayed alongside it. You could clearly see how the two are related.The Chinese README your buddies waiting for!希望有同学帮助贡献个中文 README 呀。Tests automation.Unfortunately, I am too busy (pronounced as[ˈlеizi]——lazy) to code these ideas myself. Pleasesubmit an issueto push me on. Or, PR to make it by yourself. I cannot wait to appreciate your great contribution!ReferencesInspired byVatsha/code_to_flowchartBased onadrai/flowchart.js,python ast,simonpercivall/astunparseA blog about this projectLicenseCopyright 2020-2023 CDFMLR. All rights reserved.Licensed under the MIT License.