首先使用内置模块os.
>>> import os
>>> code = os.system("pwd && sleep 2")
# /User/zhipeng
>>> print code
# 0
问题是 os.system 只能获取到结束状态
使用内置模块 subprocess
>>> import subprocess
>>> subprocess.Popen("pwd && sleep 2", shell=True, cwd="/home")
#
# /home
>>> sub = subprocess.Popen("pwd && sleep 2", shell=True, stdout=subprcess.PIPE)
>>> sub.wait()
>>> print sub.stdout.read()
# /User/zhipeng
subprocess.Popen还支持一些别的参数
bufsize,executable=None, stdin=None, stdout=None, stderr=None
preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None
universal_newlines=False, startupinfo=None, creationflags=0
使用第三方模块 sh
# pip install sh
&