作者hsinyichen (Hychen)
看板Python
标题[资讯] 在Python里执行外部程式取得结果的方法
时间Wed Dec 22 03:35:14 2010
要在Python执行外部程式, 有下列几种方法
1. 在shell执行指令
os.system("ls --all --almost-all")
2. 不另开shell
subprocess.call(['ls', '--all','-almost-all'])
我在GitPython模组上看到他用下面的方式做git binding,
# 等同 git commint arg1 arg2 --opt1 --opt2 value
git.commit(arg1, arg2, opt1=True, opt2=value)
基本上就是把 method 当成 sub command, kwargs 则
转换成 option
我觉得满好用的, 所以就把code出抽来写成一个模组,
拿来写写系统管理工具时,还满方便的
下面是简单的范例
import ucltip
ls = ucltip.SingleCmd('ls')
# 等同 ls --all --almost-all
print ls(all=True, almost_all=True)
zenity = CmdDispatcher('zneity', opt_style=1, subcmd_prefix='--')
# 等同 zneity --info --text=hi
zneity.info(text="hi")
利用这种方式写的 Zenity Binding, 只有少数几种要对执行结果需要再做处理
https://github.com/hychen/vsgui/blob/master/vsgui/zenity.py
ucltip module
http://pypi.python.org/pypi/ucltip/
--
身为一个阿宅, 在家工作也是理所当然的, 你说是吧!
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 114.36.164.40
1F:推 POSIX:push! 12/22 04:02