天天看點

python執行系統指令并取得輸出内容

方法一:

[python]  view plain copy

  1. import os  
  2. p = os.popen('uptime')  
  3. x=p.read()  
  4. print x  

方法二:

[python]  view plain copy

  1. import subprocess  
  2. res = subprocess.Popen('uptime',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)  
  3. result = res.stdout.readlines()  

補充:

方法三:

[python]  view plain copy

  1. import commands
  2. cmd = "tail -n 5 tmpfile"
  3. _, content = commands.getstatusoutput(cmd)

方法1.2轉自:http://blog.csdn.net/dingyaguang117/article/details/7236296