python调用shell命令

1、subprocess介绍

官方推荐 subprocess模块,os.system(command) 这个废弃了

亲测 os.system 使用sed需要进行字符转义,非常麻烦

python3 subprocess模块使用

2、subprocess模块使用

官网说明文档  subprocess.call 和 subprocess.check_call执行命令,返回状态码。两者唯一的区别在于返回值。执行成功,都返回 0;执行失败,check_call 将raise出来CalledProcessError。

2.1、subprocess.call () 使用

import subprocess

subprocess.call(['ls', '-l'])
subprocess.call(['ls -l'], shell=True)

注意shell=True 的用法,支持命令以字符串的形式传入。

2.2、subprocess.getoutput()使用

以字符串的形式返回执行结果,错误或者正确都会返回,命令本身不会报错
import subprocess
a = subprocess.getoutput('ls /Users/wangxiansheng/desktops')
print(a)
print(type(a))

ls: /Users/wangxiansheng/desktops: No such file or directory
<class 'str'>

变量 a 保存了错误信息并返回。

subprocess.getstatusoutput(cmd)

返回包含执行结果状态码和输出信息的元组。
import subprocess
a = subprocess.getstatusoutput('ls /Users/wangxiansheng/desktops')
print(a)
print(type(a))

(1, 'ls: /Users/wangxiansheng/desktops: No such file or directory')
<class 'tuple'>


3、python调用sed

方式一:
>>> subprocess.call(["sed","-i",r"s/hello/hi/g",'/home/b.sh'])
0


方式二:
>>> subprocess.call(["sed -i 's/hello/hi/g' /home/b.sh"], shell=True)
0


4、python调用grep

>>> subprocess.call(["cat d.txt | grep hello"], shell=True)
hello
0

>>> subprocess.call(["grep -n 'word' /root/d.txt"], shell=True)
2:word
0

5、python调用awk

>>> subprocess.call(["cat d.txt | awk '{print $1}'"], shell=True)
hello
word
come
on
0


6、python调用find

>>> subprocess.call(['find / -name b.sh'], shell=True)
/home/b.sh
0

7、subprocess怎么判断命令是否执行成功

>>> import subprocess
>>> if subprocess.call(["lss"], shell=True) !=0:
...    print('Without the command')
...
/bin/sh: lss: command not found
Without the command

在pycharm中调用shell命令

1、

# -*- coding:UTF-8 -*-
import subprocess
subprocess.call(["ls /home"], shell=True)
#subprocess.call(["cat /root/d.txt | grep hello"], shell=True)


执行结果

ssh://root@192.168.0.75:22/usr/bin/python -u /app/py_code/test3.py
b.sh oracle test

2、

# -*- coding:UTF-8 -*-
import subprocess
subprocess.call(["cat /home/b.sh"], shell=True)
subprocess.call(["sed -i 's/hi/hello/g' /home/b.sh"], shell=True)
subprocess.call(["cat /home/b.sh"], shell=True)


执行结果

ssh://root@192.168.0.75:22/usr/bin/python -u /app/py_code/test3.py
hi
hello

参考文档

https://blog.csdn.net/u010454729/article/details/46640083

https://blog.csdn.net/CityzenOldwang/article/details/78382960

https://www.cnblogs.com/xiaozhiqi/p/5814564.html

https://www.jb51.net/article/141877.htm

http://www.cnblogs.com/tomato0906/articles/4605114.html      os.system(command) 废弃了

https://cloud.tencent.com/developer/news/257058

原文地址:https://www.cnblogs.com/effortsing/p/9981998.html