最新消息:

python执行shell命令

Python admin 1474浏览 0评论

在此比较一下两种方法执行系统命令的方法,以方便于日后运用:(

1. os.system()

system(command) -> exit_status

Execute the command (a string) in a subshell.  # 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息..

 >>> os.system(‘ls’)  #如果再命令行下执行,结果直接打印出来

2.os.popen()
popen(command [, mode=’r’ [, bufsize]]) -> pipe

Open a pipe to/from a command returning a file object.  # 此种方法不但执行命令还返回执行后的信息对象

>>>tmp = os.popen('ls *.py').readlines()  

>>>tmp  

    Out[21]:   
    ['dump_db_pickle.py\n',  
     'dump_db_pickle_recs.py\n',  
     'dump_db_shelve.py\n',  
     'initdata.py\n',  
     '__init__.py\n',  
     'make_db_pickle.py\n',  
     'make_db_pickle_recs.py\n',  
     'make_db_shelve.py\n',  
     'peopleinteract_query.py\n',  
     'reader.py\n',  
     'testargv.py\n',  
     'teststreams.py\n',  
     'update_db_pickle.py\n',  
     'writer.py\n']

   将返回的结果赋于一变量,便于程序的处理.

  总结两者可知,根据不同的用途,可以合理的调用不同的方法来进行。。。

转载请注明:jinglingshu的博客 » python执行shell命令

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址