Python 中以子进程(subprocess)的形式调用其他任何程序的一个库,使用十分方便。
基本用法
调用方法
# 最简单的调用方式 from sh import ifconfig print(ifconfig("wlan0")) # 几种等价的调用方式 import sh print(sh.ls("/")) from sh import ls print(ls("/")) import sh run = sh.Command("/home/amoffat/run.sh") # Absolute path run() lscmd = sh.Command("ls") # Absolute path not needed lscmd()
多参数命令
某些命令可能需要多个参数,这时需要将它们作为string分割:
from sh import tar tar("cvf", "/tmp/test.tar", "/my/home/directory/")
Keyword参数
# resolves to "curl http://duckduckgo.com/ -o page.html --silent" curl("http://duckduckgo.com/", o="page.html", silent=True) # or if you prefer not to use keyword arguments, this does the same thing: curl("http://duckduckgo.com/", "-o", "page.html", "--silent") # resolves to "adduser amoffat --system --shell=/bin/bash --no-create-home" adduser("amoffat", system=True, shell="/bin/bash", no_create_home=True) # or adduser("amoffat", "--system", "--shell", "/bin/bash", "--no-create-home")
后台运行
默认情况下,每条调用的命令依次执行,程序等待调用的命令执行完毕后再继续往下执行。可以通过 _bg=True
来设置后台运行:
# blocks sleep(3) print("...3 seconds later") # doesn't block p = sleep(3, _bg=True) print("prints immediately!") p.wait() print("...and 3 seconds later")
管道
sh同样支持bash的管道形式,只需要把每个命令作为参数传递给下一个调用的命令:
# print(the number of folders and files in /etc print(wc(ls("/etc", "-1"), "-l"))
子命令
某些命令具有子命令集,如 git (push, pull), sudo 等,在 sh 中可以通过属性的方式调用:
from sh import git, sudo # resolves to "git branch -v" print(git.branch("-v")) print(git("branch", "-v")) # the same command # resolves to "sudo /bin/ls /root" print(sudo.ls("/root")) print(sudo("/bin/ls", "/root")) # the same command
Exit Codes
大部分进程执行完成后的 exit code
为0,可以通过 exit_code
查看:
output = ls("/") print(output.exit_code) # should be 0
高级特性
with
with sudo: print(ls("/root"))
iterate
通过指定 _iter=True
from sh import tail # runs forever for line in tail("-f", "/var/log/some_log_file.log", _iter=True): print(line)
参考:
Add Comment