代码如下:
output = os.popen('cat /proc/cpuinfo')
print output.read()
通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。但是无法读取程序执行的返回值)
尝试第三种方案 commands.getstatusoutput() 一个方法就可以获得到返回值和输出,非常好用。
❷ 怎么样在shell脚本中调用python脚本
1、os.system(cmd)
缺点:不能获取返回值
2、os.popen(cmd)
要得到命令的输出内容,只需再调用下read()或readlines()等
例:a=os.popen(cmd).read()
3、commands模块,其实也是对popen的封装。
此模块主要有如下方法:
commands.getstatusoutput(cmd)返回(status, output).
commands.getoutput(cmd)只返回输出结果
commands.getstatus(file)返回ls -ld file的执行结果字符串,调用了getoutput
例:
>>> 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-x1 root13352 Oct 141994 /bin/ls'
来源:麦子学院
❸ python怎么执行shell命令
工具/原料
Python环境
方法/步骤
os.system("The command you want"). 这个调用相当直接,且是同步进行的,程序需要阻塞并等待返回。返回值是依赖于系统的,直接返回系统的调用返回值,所以windows和linux是不一样的
os.popen(command[,mode[,bufsize]]),
图中是一个例子.
可以看出,popen方法通过p.read()获取终端输出,而且popen需要关闭close().当执行成功时,close()不返回任何值,失败
时,close()返回系统返回值. 可见它获取返回值的方式和os.system不同。
使用commands模块,图中是一组例子。根据你需要的不同,commands模块有三个方法可供选择。getstatusoutput, getoutput, getstatus。
但是,如上三个方法都不是Python推荐的方法,而且在Python3中其中两个已经消失。Python文档中目前全力推荐第四个方法,subprocess! subprocess使用起来同样简单:
直
接调用命令,返回值即是系统返回。shell=True表示命令最终在shell中运行。Python文档中出于安全考虑,不建议使用
shell=True。建议使用Python库来代替shell命令,或使用pipe的一些功能做一些转义。官方的出发点是好的,不过真心麻烦了很多,
so.... 如果你更关注命令的终端输出,可以如下图这样操作, 同样很简单.
❹ python调用shell脚本 获取shell脚本中间的输出值
import os
ss=os.popen("sh test.sh").readlines()
print ss
❺ python 通过subprocess.run调用ubuntu shell脚本 返回值为0却不打印输出
应该用格式化串传进去
'/home/.../test.sh %s' % v
❻ 我在shell里调用一个PYTHON脚本,怎么拿到这个PYTHON脚本的错误输出
执行如下shell命令:
$ python my.py > out.txt 2> err.txt
则err.txt中会存有执行脚本my.py的错误输出,out.txt中会含有正常的print结果。
❼ 请教在shell中调用python并获取py返回值的问题
调用并且传入参数就不必说了吧,很简单直接python <file_name>.py <arg1> <arg2>
首先,你知道PYTHON是买有main函数的,要想读到PYTHON里面RETURN的值恐怕办不到PYTHON里面也没有类似的通道。
但是,你却可以读到PYTHON的sterr的error code。PYTHON里面有个sys模块,你可以用sys.exit(<num>)的方式,通过把错误码发送给stderr。然后再Shell里面用$?(事实上$?命令会从stderr里面去读) 来判断python是否执行成功
❽ 如何使用python脚本调用adb shell里面的命令
python调用Shell脚本,有两种方法:os.system(cmd)或os.popen(cmd),前者返回值是脚本的退出状态码,后者的返回值是脚本执行过程中的输出内容。实际使用时视需求情况而选择。
现假定有一个shell脚本
test.sh:
#!/bin/bash
echo "hello world!"
exit 3
❾ 参数传递:shell脚本调用一个带参数的python函数
把a b c写到文件里,如example.txt,然后shell里:cif filename <example.txt
❿ shell脚本中怎么调用python脚本中的带参函数
Python 可以利用 sys.argv 拿到命令列上的 arguments:
$ python test.py 1 2 3
test.py:
import sys
print(sys.argv)
结果:
['test.py', '1', '2', '3']
所以你在 build_using_xctool.sh 中可以这样调度 python:
python /Users/gyd/Desktop/auto_send_email.py subject msg toaddrs fromaddr smtpaddr password
然后在 auto_send_email.py 中:
import sys # 自己 import sys...if __name__ == '__main__':
sendmail(*sys.argv[1:])