I'm interested in writing a python binding or wrapper for an existing command line utility that I use on Linux, so that I can access its features in my python programs. Is there a standard approach to doing this that someone could point me to?
At the moment, I have wrapped the comman开发者_开发知识库d line executable in a subprocess.Popen call, which works but feels quite brittle, and I'd like to make the integration between the two sides much more stable so that it works in places other than my own computer!
If you must use a command line interface, then subprocess.Popen is your best bet. Remember that you can use shell=True to let it pick the path variables, you can use os.path.join to use OS-dependent path separators etc.
If, however, your command line utility has shared libraries, look at ctypes, which allows you to connect directly to those libraries and expose functionality directly.
One way would be to
re-factor your command line utility so that command line handling is separated and the actual functionality is exposed as shared archive.
Then you could expose those function using cython.
Write your complete command line utility in python that exploits those functions.
This makes distribution hard though.
What you are doing is still the best way.
精彩评论