搜索
首页后端开发Python教程利用python3实现Linux的脚本功能

利用python3实现Linux的脚本功能

Apr 19, 2019 am 11:27 AM
linuxpython3shell

Python 3的更新已经有一段时间了,相比较于Python2也有许多不同的改变,Python 3 在Linux中也是利用比较多的,这里主要实践了一些Python3利用Linux的脚本执行命令。

首先,如果只需要执行,或者只需要得到执行的状态可以用 os.system 调用

#!/usr/bin/env python3
print ('hello,world')
import os
val2 =  os.system('cd trb && cd trb')
val3 = os.system('ls')
print('val2 is ',val2)

上述代码。如果val2内代码执行成功,即有两级trb文件夹,则val2 的值是0  否则是256

两行调用没有继承性,如果要连续执行就在一个语句里加 && (Shell 语法)

在print之前,屏幕还会显示执行的结果

hello,worldsh: line 0: cd: trb: 没有那个文件或目录
Abcd.py  automesh.sh  Cal_Ori  fold.txt  Linux_py_temp.py  meshedjob.rec  new_geom  onc143314  trb
val2 is  256

os.popen(cmd)方法,只能得到运行的输出,但是如果不print屏幕上就什么也没有。

例如

val4 = os.popen('cd trb && cd trb')
val5 = os.popen('ls')print('开始PRINT')print(val4.read())print(val5.read())

显示如下

hello,world
开始PRINT/bin/sh: line 0: cd: trb: 没有那个文件或目录
Abcd.py
automesh.shCal_Ori
fold.txt
Linux_py_temp.py
meshedjob.rec
new_geom
onc143314
trb

这里输出是类文件的对象,要调用read或者readlines读取也可以用来遍历。

############

终极武器,subprocess

py3.5后建议使用的模块subprocess

网上教程里的commands 是2里的功能,在3里被删除,但是可以通过subprocess调用

有以下命令:

subprocess.getstatusoutputcmd 

在shell中返回执行cmd<span class="pre">(status, <span class="pre">output) 返回2个元素的元组</span></span>

3.4之后添加win支持

subprocess.getoutputcmd 

执行cmd然后返回结果

legacycmd = subprocess.getstatusoutput('ls -l')print('subprocess.getstatusoutput 输出',legacycmd)
legacycmd2 = subprocess.getoutput('ls -l')print('subprocess.getoutput 输出',legacycmd2)

上面为代码

输出:

subprocess.getstatusoutput 输出 (0, &#39;总用量 48\n-rwxr--r-- 1 para036 bjpara  516 4月  16 2018 Abcd.py\n-rwxr--r-- 1 para036 bjpara 1619 4月  16 16:58                     automesh_onpsn_fortest.sh\n-rwxr--r-- 1 para036 bjpara 1616 4月  15 14:31 automesh.sh\ndrwxr-xr-x 5 para036 bjpara 4096 4月  15 14:31 Cal_Ori\n-rw-r                    --r-- 1 para036 bjpara   32 4月  16 16:56 fold.txt\n-rwxr--r-- 1 para036 bjpara 1530 4月  15 14:45 Linux_py_temp.py\n-rw-r--r-- 1 para036 bjpara   27                     4月  15 14:43 meshedjob.rec\ndrwxr-xr-x 2 para036 bjpara 4096 4月  15 14:31 new_geom\ndrwxr-xr-x 5 para036 bjpara 4096 4月  15 14:51 onc143314\ndrwx                    r-xr-x 5 para036 bjpara 4096 4月  16 17:05 onc16165650\ndrwxr-xr-x 5 para036 bjpara 4096 4月  16 16:46 onc163840\ndrwxr-xr-x 2 para036 bjpara 4096 4                    月  15 14:32 trb&#39;)
subprocess.getoutput 输出 总用量 48
-rwxr--r-- 1 para036 bjpara  516 4月  16 2018 Abcd.py
-rwxr--r-- 1 para036 bjpara 1619 4月  16 16:58 automesh_onpsn_fortest.sh
-rwxr--r-- 1 para036 bjpara 1616 4月  15 14:31 automesh.sh
drwxr-xr-x 5 para036 bjpara 4096 4月  15 14:31 Cal_Ori
-rw-r--r-- 1 para036 bjpara   32 4月  16 16:56 fold.txt
-rwxr--r-- 1 para036 bjpara 1530 4月  15 14:45 Linux_py_temp.py
-rw-r--r-- 1 para036 bjpara   27 4月  15 14:43 meshedjob.rec
drwxr-xr-x 2 para036 bjpara 4096 4月  15 14:31 new_geom
drwxr-xr-x 5 para036 bjpara 4096 4月  15 14:51 onc143314
drwxr-xr-x 5 para036 bjpara 4096 4月  16 17:05 onc16165650
drwxr-xr-x 5 para036 bjpara 4096 4月  16 16:46 onc163840
drwxr-xr-x 2 para036 bjpara 4096 4月  15 14:32 trb

  其中output是字符串。如果不print就不显示

新的版本推荐使用subprocess.run() 来解决一般问题。 

subprocess.run()、subprocess.call()、subprocess.check_call()和subprocess.check_output()都是通过对subprocess.Popen的封装来实现的高级函数,因此如果我们需要更复杂功能时,可以通过subprocess.Popen来完成

run默认不会返回输出,只返回命令和执行状态

recomd = subprocess.run(['ls','-l'])#等待命令执行完成后会在屏幕输出执行结果,然后返回一个包含执行结果的CompletedProcess类的实例。print('输出recmd\n',recomd)print(recomd.returncode)

输出如下:

 如果要返回输出,要添加参数,传递subprocess.PIPE给stdout和stderr,然后可以通过返回的CompletedProcess类实例的stdout和stderr属性或捕获相应的内容;

universal_newlines: 该参数影响的是输入与输出的数据格式,比如它的值默认为False,此时stdout和stderr的输出是字节序列;当该参数的值设置为True时,stdout和stderr的输出是字符串。

总代码如下:

#!/usr/bin/env python3
print (&#39;hello,world&#39;)
import os
# val2 =  os.system(&#39;cd trb && cd trb&#39;)
# val3 = os.system(&#39;ls&#39;)
# print(&#39;val2 is &#39;,val2)
# val4 = os.popen(&#39;cd trb && cd trb&#39;)
# val5 = os.popen(&#39;ls&#39;)
# print(&#39;开始PRINT&#39;)
# print(val4.read())
# print(val5.read())
import subprocess
recomd = subprocess.run([&#39;ls&#39;,&#39;-l&#39;])
#等待命令执行完成后会在屏幕输出执行结果,然后返回一个包含执行结果的CompletedProcess类的实例。
print(&#39;输出recmd\n&#39;,recomd)
print(recomd.returncode)
print(&#39;传递参数&#39;)
recomdouterr = subprocess.run( [&#39;ls&#39;,&#39;-l&#39;],stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True)
print(&#39;输出outerr&#39;,recomdouterr.stdout,recomdouterr.stderr)
print(&#39;传递参数2&#39;)
recomdouterr = subprocess.run( [&#39;ls&#39;,&#39;-l&#39;],stdout=subprocess.PIPE,universal_newlines=True)
print(&#39;输出outerr&#39;,recomdouterr.stdout)
print(len( recomdouterr.stdout.strip().split(&#39;\n&#39;) ))
print(recomdouterr.stdout.strip().split(&#39;\n&#39;)[-1])
# legacycmd = subprocess.getstatusoutput(&#39;ls -l&#39;)
#
# print(&#39;subprocess.getstatusoutput 输出&#39;,legacycmd)
#
# legacycmd2 = subprocess.getoutput(&#39;ls -l&#39;)
#
# print(&#39;subprocess.getoutput 输出&#39;,legacycmd2)

 参考资料:python3.5 官方文档 : https://docs.python.org/3.5/library/subprocess.html

Python的使用途径越来越广泛了,而Linux作为服务器端也是大有作为,使用Python来实现Linux的脚本操作,简化了服务器端的操作,提高了可控性。

以上是利用python3实现Linux的脚本功能的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:cnblogs。如有侵权,请联系admin@php.cn删除
Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解释吗?揭穿神话Python:它是真正的解释吗?揭穿神话May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

与同一元素的Python串联列表与同一元素的Python串联列表May 11, 2025 am 12:08 AM

concateNateListsinpythonwithTheSamelements,使用:1)operatototakeepduplicates,2)asettoremavelemavphicates,or3)listCompreanspearensionforcontroloverduplicates,每个methodhasdhasdifferentperferentperferentperforentperforentperforentperfortenceandordormplications。

解释与编译语言:Python的位置解释与编译语言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允许ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循环时:您什么时候在Python中使用?循环时:您什么时候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!