在Python中调用linux命令

在Python中调用linux命令,第1张

目的:用Python做出全自动化的pipline,用于rrbs

最近有个需求就是页面上执行shell命令,第一想到的就是os.system,

os.system('cat /proc/cpuinfo')

但是发现页面上打印的命令执行结果 0或者1,当然不满足需求了。

尝试第二种方案 os.popen()

output = os.popen('cat /proc/cpuinfo')printoutput.read()

通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的 *** 作可以看到执行的输出。但是无法读取程序执行的返回值)

尝试第三种方案 commands.getstatusoutput() 一个方法就可以获得到返回值和输出,非常好用。

(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')printstatus, output

Python Document 中给的一个例子,

>>>import commands>>>commands.getstatusoutput('ls /bin/ls')

(0, '/bin/ls')>>>commands.getstatusoutput('cat /bin/junk')

(256,'cat: /bin/junk: No such file or directory')>>>commands.getstatusoutput('/bin/junk')

(256,'sh: /bin/junk: not found')>>>commands.getoutput('ls /bin/ls')'/bin/ls'>>>commands.getstatus('/bin/ls')'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

最后页面上还可以根据返回值来显示命令执行结果。

1)打开mac终端,输入指令(项目所在位置/Users/kaka/Desktop/code/ssrpg-locust-slt ,即将本地电脑上的ssrpg-locust-slt项目拷贝到远程的code目录下)

scp /Users/dingyuanlin/Desktop/code/ssrpg-locust-slt root@172.20.8.183 :/code/

2)进入服务器linux环境,可在/code/目录下查看到复制的文件

3)在linux环境下查看python环境是否ok

a)先查看python3,安装python3版本

b)查看是否安装pip ——pip -V可查看,若无 执行如下指令

curl https://bootstrap.pypa.io/get-pip.py | python3

yum install gcc python-devel

pip install -r requirements.txt

c)安装redis

yum install epel-release

yum repolist

yum install redis

d)启动redis服务

service redis start

e)python3 run.py

注意 :

1. 拷贝的命令是需要在客户端执行,即当前文件夹在哪个位置就需要从哪个系统控制台输入命令

2. mac系统下使用brew,而centos系统下需要使用yum命令

3. nohup redis-server >web6.log 2>&1 </dev/null&(nohup表示永久运行,&表示后台运行,该指令为redis服务后台运行)

先将终端所在路径切换到python脚本文件的目录下,

然后给脚本文件运行权限,一般755就OK。

chmod 755 ./*.py

然后执行。

在linux命令行模式中运行python,进入python交互式环境,写程序后直接输出结果。

运行Python py源文件的方式不需要py源文件有可执行权限,方法是用Python命令加py文件名的形式来运行源文件,如果是Python 2.x的Python源文件,就用python命令执行:python 文件名;如果是Python 3的Python源文件,就用python3命令执行:python3 文件名。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/6228337.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-03-18
下一篇2023-03-18

发表评论

登录后才能评论

评论列表(0条)

    保存