Python执行shell命令相关

导语

在编写python脚本的时候,偶尔想调用shell命令来执行一些操作会比较方便些。python中目前有多种方法可以达到这样的目的,有的仅仅是执行命令不返回需要的结果,有些可以返回执行的结果保存到变量,以便于后续操作

涉及到的模块有 os.systemcommandssubprocess


下面以具体的例子说明情况

#!/usr/bin/env bash 

import os
import commands
import subprocess

# -- os.system() --
# execute shell command in sub-terminal and can not get the return result
result1 = os.system('ls -l .')
print('result: ')
print(result1)
print('----------------------------------------')

# -- os.popen() --
# execute and can get the return result
result2 = os.popen('ls -l')
# file type
print('type: ', type(result2))

result3 = os.popen('ls -l').readlines()
# list file
print('type: ', type(result3))
print('result: ')
print(result3)
print('----------------------------------------')

# -- commands --
# import commands
# method:
#   getoutput
#   getstatusoutput
result4 = commands.getoutput('ls -l')
print('result: ')
print(result4)
print('=======')
result5_status, result5_output = commands.getstatusoutput('ls -l')
print('status: ', result5_status)
print('output: ')
print(result5_output)
print('----------------------------------------')



# subprocess
# import subprocess
# method:
#   call(["cmd","arg1", "arg2"], shell=True) refer to os.system()
#   Popen("cmd", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) refer to os.popen
#
#result6 = subprocess.call("ls -l", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p = subprocess.Popen('ls *.txt', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print(p.stdout.readlines())

for line in p.stdout.readlines():
    print line,

## wait for child process to terminate, and turn returncode
retval = p.wait()
##  if ok, return 0
print(retval)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 其实应该搞清楚何时要用python写脚本,何时用shell例如对于系统操作的业务,我倾向于用shell awk ...
    帅子锅阅读 13,170评论 0 6
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    aimaile阅读 26,855评论 6 427
  • From: https://blog.linuxeye.com/375.html 从Python 2.4开始,Py...
    pzka158阅读 3,129评论 0 2
  • 荷花大家都会不陌生,说起描写荷花的诗句,想必大家都会想到爱莲说中的“予独爱莲之出淤泥而不染,濯清涟而不妖”一句诗。...
    新眸阅读 689评论 0 2
  • 块元素:主要特征是会产生换行效果,自动与其他元素分离成两行;通常可以作为容器在内部添加其他元素。 内联元素:不会产...
    frankisbaby阅读 642评论 0 0

友情链接更多精彩内容