Scripting inside a Python application

前端 未结 4 1956
清歌不尽
清歌不尽 2021-01-19 00:50


I\'d like to include Python scripting in one of my applications, that is written in Python itself.

My application must be able to call extern

4条回答
  •  长情又很酷
    2021-01-19 01:01

    If you'd like the user to interactively enter commands, I can highly recommend the code module, part of the standard library. The InteractiveConsole and InteractiveInterpreter objects allow for easy entry and evaluation of user input, and errors are handled very nicely, with tracebacks available to help the user get it right.

    Just make sure to catch SystemExit!

    $ python
    Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) 
    [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> shared_var = "Set in main console"
    >>> import code
    >>> ic = code.InteractiveConsole({ 'shared_var': shared_var })
    >>> try:
    ...     ic.interact("My custom console banner!")
    ... except SystemExit, e:
    ...     print "Got SystemExit!"
    ... 
    My custom console banner!
    >>> shared_var
    'Set in main console'
    >>> shared_var = "Set in sub-console"
    >>> sys.exit()
    Got SystemExit!
    >>> shared_var
    'Set in main console'
    

提交回复
热议问题