I am trying to write an app in python to control a motor using serial. This all works in a CLI situation fine and is generally stable. but I was wondering how simple it was
is there a simple way of detecting something like GTK, so it only applied the code when GTK was present?
First, break your app into 3 separate modules.
The actual work: foo_core.py
.
A CLI module that imports foo_core
. Call it foo_cli.py
.
A GUI module that imports foo_core
. Call it foo_gui.pyw
.
The foo_cli
module looks like this.
import foo_core
import optparse
def main():
# parse the command-line options
# the real work is done by foo_core
if __name__ == "__main__":
main()
The foo_gui
module can look like this.
import foo_core
import gtk # or whatever
def main()
# build the GUI
# real work is done by foo_core under control of the GUI
if __name__ == "__main__":
main()
That's generally sufficient. People can be trusted to decide for themselves if they want CLI or GUI.
If you want to confuse people, you can write a foo.py
script that does something like the following.
try:
import foo_gui
foo_gui.main()
except ImportError:
import foo_cli
foo_cli.main()