python shell命令-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

变量 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")

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值