【python】os.system() os.popen() 在 python 执行 cmd 指令

news2024/10/7 18:23:46

先说总结

os.system:获取程序执行命令的返回值。
os.popen: 获取程序执行命令的输出结果。
commands:获取返回值和命令的输出结果。

1 os.system()

这个方法是直接调用标准C的system() 函数,仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息,但是会在python终端中打印输出。

os.system(cmd)的返回值。os.system(cmd)的返回值只会有0(成功),1,2。
如果执行成功,那么会返回0,表示命令执行成功。否则,则是执行错误。

脚本退出码

参考:https://blog.csdn.net/qq_36380748/article/details/106787911
可以自己设定 sh 脚本,在脚本中插入返回码,这样就不会返回 0 了,而是返回码。

#!/bin/bash
 
echo "hello world!"
 
exit 1

我们使用os.system()执行脚本:

 
>>> import os
>>> cmd='./test.sh'
>>> mm=os.system(cmd)
hello world!
>>> print (mm)
256

可以看到shell脚本执行完成后,返回的值是256,但是跟我们实际想要的值不一样:

os.system的返回值并不是执行程序的返回结果。而是一个16位的数,它的高位才是返回码。也就是说os.system()返回256即 0×0100,返回码应该是其高位0×01即1。

使用os.system返回值是脚本的退出状态码,该方法在调用完shell脚本后,返回一个16位的二进制数,低位为杀死所调用脚本的信号号码,高位为脚本的退出状态码。

os.system()返回值为0 linux命令返回值也为0。一般来说,返回 0 表示运行成功。

os.system()返回值为256,十六位二进制数示为:00000001,00000000,高八位转成十进制为 1 对应 linux命令返回值 1。

os.system()返回值为512,十六位二进制数示为:00000010,00000000,高八位转成十进制为 2 对应 linux命令返回值 2。

2 os.popen()

os.popen()方法不仅执行命令而且返回执行后的信息对象(常用于需要获取执行命令后的返回信息),是通过一个管道文件将结果返回。通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。
os.popen(cmd)会把执行的cmd的输出作为值返回。

import os
result = os.popen('cat /etc/passwd')
print(result.read())

对比不同

def ping2(host, n):
    cmd = "ping {} {} {}".format(
        "-n" if sys.platform.lower() == "win32" else "-c",
        n,
        host,
    )
    return cmd, os.system(cmd)
    
def ping3(host, n):
    cmd = "ping {} {} {}".format(
        "-n" if sys.platform.lower() == "win32" else "-c",
        n,
        host,
    )
    return cmd, os.popen(cmd)

在这里插入图片描述
探究 ping3 输出的那个到底是啥:
在这里插入图片描述

3 commands 模块

import commands
status = commands.getstatus('cat /etc/passwd')
print(status)
output = commands.getoutput('cat /etc/passwd')
print(output)
(status, output) = commands.getstatusoutput('cat /etc/passwd')
print(status, output)

os.system() 返回结果大全

code 0 : succcessful
"OS error code   1:  Operation not permitted"
 "OS error code   2:  No such file or directory"
 "OS error code   3:  No such process"
 "OS error code   4:  Interrupted system call"
 "OS error code   5:  Input/output error"
 "OS error code   6:  No such device or address"
 "OS error code   7:  Argument list too long"
 "OS error code   8:  Exec format error"
 "OS error code   9:  Bad file descriptor"
 "OS error code  10:  No child processes"
 "OS error code  11:  Resource temporarily unavailable"
 "OS error code  12:  Cannot allocate memory"
 "OS error code  13:  Permission denied"
 "OS error code  14:  Bad address"
 "OS error code  15:  Block device required"
 "OS error code  16:  Device or resource busy"
 "OS error code  17:  File exists"
 "OS error code  18:  Invalid cross-device link"
 "OS error code  19:  No such device"
 "OS error code  20:  Not a directory"
 "OS error code  21:  Is a directory"
 "OS error code  22:  Invalid argument"
 "OS error code  23:  Too many open files in system"
 "OS error code  24:  Too many open files"
 "OS error code  25:  Inappropriate ioctl for device"
 "OS error code  26:  Text file busy"
 "OS error code  27:  File too large"
 "OS error code  28:  No space left on device"
 "OS error code  29:  Illegal seek"
 "OS error code  30:  Read-only file system"
 "OS error code  31:  Too many links"
 "OS error code  32:  Broken pipe"
 "OS error code  33:  Numerical argument out of domain"
 "OS error code  34:  Numerical result out of range"
 "OS error code  35:  Resource deadlock avoided"
 "OS error code  36:  File name too long"
 "OS error code  37:  No locks available"
 "OS error code  38:  Function not implemented"
 "OS error code  39:  Directory not empty"
 "OS error code  40:  Too many levels of symbolic links"
 "OS error code  42:  No message of desired type"
 "OS error code  43:  Identifier removed"
 "OS error code  44:  Channel number out of range"
 "OS error code  45:  Level 2 not synchronized"
 "OS error code  46:  Level 3 halted"
 "OS error code  47:  Level 3 reset"
 "OS error code  48:  Link number out of range"
 "OS error code  49:  Protocol driver not attached"
 "OS error code  50:  No CSI structure available"
 "OS error code  51:  Level 2 halted"
 "OS error code  52:  Invalid exchange"
 "OS error code  53:  Invalid request descriptor"
 "OS error code  54:  Exchange full"
 "OS error code  55:  No anode"
 "OS error code  56:  Invalid request code"
 "OS error code  57:  Invalid slot"
 "OS error code  59:  Bad font file format"
 "OS error code  60:  Device not a stream"
 "OS error code  61:  No data available"
 "OS error code  62:  Timer expired"
 "OS error code  63:  Out of streams resources"
 "OS error code  64:  Machine is not on the network"
 "OS error code  65:  Package not installed"
 "OS error code  66:  Object is remote"
 "OS error code  67:  Link has been severed"
 "OS error code  68:  Advertise error"
 "OS error code  69:  Srmount error"
 "OS error code  70:  Communication error on send"
 "OS error code  71:  Protocol error"
 "OS error code  72:  Multihop attempted"
 "OS error code  73:  RFS specific error"
 "OS error code  74:  Bad message"
 "OS error code  75:  Value too large for defined data type"
 "OS error code  76:  Name not unique on network"
 "OS error code  77:  File descriptor in bad state"
 "OS error code  78:  Remote address changed"
 "OS error code  79:  Can not access a needed shared library"
 "OS error code  80:  Accessing a corrupted shared library"
 "OS error code  81:  .lib section in a.out corrupted"
 "OS error code  82:  Attempting to link in too many shared libraries"
 "OS error code  83:  Cannot exec a shared library directly"
 "OS error code  84:  Invalid or incomplete multibyte or wide character"
 "OS error code  85:  Interrupted system call should be restarted"
 "OS error code  86:  Streams pipe error"
 "OS error code  87:  Too many users"
 "OS error code  88:  Socket operation on non-socket"
 "OS error code  89:  Destination address required"
 "OS error code  90:  Message too long"
 "OS error code  91:  Protocol wrong type for socket"
 "OS error code  92:  Protocol not available"
 "OS error code  93:  Protocol not supported"
 "OS error code  94:  Socket type not supported"
 "OS error code  95:  Operation not supported"
 "OS error code  96:  Protocol family not supported"
 "OS error code  97:  Address family not supported by protocol"
 "OS error code  98:  Address already in use"
 "OS error code  99:  Cannot assign requested address"
 "OS error code 100:  Network is down"
 "OS error code 101:  Network is unreachable"
 "OS error code 102:  Network dropped connection on reset"
 "OS error code 103:  Software caused connection abort"
 "OS error code 104:  Connection reset by peer"
 "OS error code 105:  No buffer space available"
 "OS error code 106:  Transport endpoint is already connected"
 "OS error code 107:  Transport endpoint is not connected"
 "OS error code 108:  Cannot send after transport endpoint shutdown"
 "OS error code 109:  Too many references: cannot splice"
 "OS error code 110:  Connection timed out"
 "OS error code 111:  Connection refused"
 "OS error code 112:  Host is down"
 "OS error code 113:  No route to host"
 "OS error code 114:  Operation already in progress"
 "OS error code 115:  Operation now in progress"
 "OS error code 116:  Stale NFS file handle"
 "OS error code 117:  Structure needs cleaning"
 "OS error code 118:  Not a XENIX named type file"
 "OS error code 119:  No XENIX semaphores available"
 "OS error code 120:  Is a named type file"
 "OS error code 121:  Remote I/O error"
 "OS error code 122:  Disk quota exceeded"
 "OS error code 123:  No medium found"
 "OS error code 124:  Wrong medium type"
 "OS error code 125:  Operation canceled"
 "OS error code 126:  Required key not available"
 "OS error code 127:  Key has expired"
 "OS error code 128:  Key has been revoked"
 "OS error code 129:  Key was rejected by service"
 "OS error code 130:  Owner died"
 "OS error code 131:  State not recoverable"

参考文献:
https://blog.csdn.net/qq_39426934/article/details/85559644?utm_medium=distribute.pc_relevant.none-task-blog-2defaultbaidujs_baidulandingword~default-1-85559644-blog-106787911.pc_relevant_recovery_v2&spm=1001.2101.3001.4242.2&utm_relevant_index=4

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/77133.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

作业-12.9【手动实现封装栈、队列模板类】

代码实现 #include <iostream> #include <queue> using namespace std; template <typename T> class My_queues { private: //队列数据存储空间 T *data; //头下标 int head; //尾下标 int tail; int max_len; public: //无参构造函数 My_queues():data(NUL…

信息搜集方法总结

文章目录前言一、域名和IP信息搜集&#xff08;一&#xff09;判断是否使用CDN&#xff08;二&#xff09;存在CND时查找真实IP&#xff08;三&#xff09;WHOIS信息查询&#xff08;四&#xff09;备案信息查询&#xff08;五&#xff09;给定IP反查其他信息&#xff08;六&am…

实现微信通知提醒的方法总结

一、使用企业微信群机器人接口效果&#xff1a;微信群消息通知优点&#xff1a;后台运行不受干扰性能稳定、群内多人同时接收通知、无需登录微信、支持微信图文消息缺点&#xff1a;只适用于企业微信群、有发送频率限制使用方法&#xff1a; 1、拉一个企业微信群&#xff0c;在…

TACL 2022 | GAL:合成文本在自然语言处理任务中的应用

©PaperWeekly 原创 作者 | 何玄黎单位 | 伦敦大学学院&#xff08;UCL&#xff09;研究方向 | 自然语言处理论文标题&#xff1a;Generate, Annotate, and Learn: NLP with Synthetic Text收录会议&#xff1a;TACL 2022论文链接&#xff1a;https://arxiv.org/abs/2106.…

无需注册试用ChatGPT

无需注册试用ChatGPT OpenAI账号有诸多限制&#xff0c;包括地区限制&#xff0c;手机号注册等&#xff0c;参考ChatGPT注册试用全攻略。不开全局代理&#xff0c;还会出现Not available OpenAIs services are not available in your country. 所以有没有什么途径&#xff0c;…

ADI Blackfin DSP处理器-BF533的开发详解17:IIS+AUDIO音频codec的应用(含源代码)

硬件准备 ADSP-EDU-BF533&#xff1a;BF533开发板 AD-HP530ICE&#xff1a;ADI DSP仿真器 软件准备 Visual DSP软件 硬件链接 很早期做的设计&#xff0c;用的是TI的一颗音频codec&#xff0c;如果要放到今天&#xff0c;我肯定是用ADI的SigmaDSP了&#xff0c;ADI所有的Si…

【计算机图形学入门】笔记5:光栅化(三角形的离散化)

目录05光栅化&#xff08;三角形的离散化&#xff09;1.Canonical Cube to Screen 从标准立方体到屏幕1.屏幕是什么&#xff1f;What is a screen?2.光栅化是什么&#xff1f;Raster screen in German3.像素Pixel (FYI, short for “picture element”)4.使用以下矩阵公式将中…

基于蜂虎狩猎 (BEH) 算法求解单目标优化问题附matlab代码

✅作者简介&#xff1a;热爱科研的Matlab仿真开发者&#xff0c;修心和技术同步精进&#xff0c;matlab项目合作可私信。 &#x1f34e;个人主页&#xff1a;Matlab科研工作室 &#x1f34a;个人信条&#xff1a;格物致知。 更多Matlab仿真内容点击&#x1f447; 智能优化算法 …

【克罗地亚VS巴西】和【荷兰VS阿根廷】足球的魅力

两场球赛你看了吗时间段克罗地亚 VS 巴西荷兰 VS 阿根廷最后的话时间段 &#x1f34b;12月09日的 23:00 克罗地亚 VS 巴西 &#x1f34a;12月10日的 03:00 荷兰 VS 阿根廷 克罗地亚 VS 巴西 半场比赛双方都没有找到绝佳的破门良机&#xff0c;0-0战平。 90分钟内&#xff…

Java的线程及多线程

1 线程 1.1 Thread 下面是两个demo&#xff0c;第一个是线程执行顺序&#xff0c;第二个是多个线程的顺序。 其中线程的start可以看成是就绪状态&#xff0c;cpu并不一定会马上去执行run方法的内容&#xff0c;因此如果是多线程&#xff0c;顺序是不确定的。 public class Th…

【Pytorch】第 6 章 :用函数逼近扩展学习

&#x1f50e;大家好&#xff0c;我是Sonhhxg_柒&#xff0c;希望你看完之后&#xff0c;能对你有所帮助&#xff0c;不足请指正&#xff01;共同学习交流&#x1f50e; &#x1f4dd;个人主页&#xff0d;Sonhhxg_柒的博客_CSDN博客 &#x1f4c3; &#x1f381;欢迎各位→点赞…

【GRU回归预测】基于门控循环单元GRU实现数据多维输入单输出回归预测附matlab代码

✅作者简介&#xff1a;热爱科研的Matlab仿真开发者&#xff0c;修心和技术同步精进&#xff0c;matlab项目合作可私信。 &#x1f34e;个人主页&#xff1a;Matlab科研工作室 &#x1f34a;个人信条&#xff1a;格物致知。 更多Matlab仿真内容点击&#x1f447; 智能优化算法 …

英方软件通过注册:预计年营收2亿 为胡军擎与江俊夫妻店

雷递网 雷建平 12月8日上海英方软件股份有限公司&#xff08;简称&#xff1a;“英方软件”&#xff09;日前通过注册&#xff0c;准备在科创板上市。英方软件计划募资5.7亿元&#xff0c;其中&#xff0c;2.46亿元用于行业数据安全和业务连续性及大数据复制软件升级项目&#…

JavaScript:错误处理

一个优秀的产品&#xff0c;需要有一个良好的错误处理策略可以让用户知道到底发生什么。不至于让用户自己不知道发生了什么&#xff0c;然后再重试或者是不至于然用户感到特别厌烦&#xff0c;然后直接离开。 try/catch语句 try/catch语句&#xff0c;在JavaScript中作为处理…

51 java.lang.Class/java.lang.ClassLoader/InstanceKlass/ClassloaderData 的卸载

前言 之前 碰到了一个 flink 基于 ChildFirstClassLoader 来进行任务隔离 导致的内存泄漏的问题 然后 使用 demo 复现了一下 问题 之后 想探索一下 java language 中 类型的卸载相关 并且会 拓展一些其他的知识 以下测试用例基于 jdk8, 部分截图基于 jdk9 测试用例 T…

0行代码拿210万年薪,ChatGPT催生新型「程序员」岗:工作纯靠和AI聊天

梦晨 发自 凹非寺量子位 | 公众号 QbitAI靠玩ChatGPT&#xff0c;还能找到新工作&#xff1f;没错&#xff0c;Riley Goodside&#xff08;后面叫他好面哥&#xff09;4月份开始在网上发布玩GPT-3的心得。最近ChatGPT一波爆火&#xff0c;他不光粉丝涨了一万多&#xff0c;还收…

『 云原生·Docker』Docker中部署Nginx

系列文章目录 本系列主要分为以下六大部分,正在更新中,尽请期待&#xff01; 『 云原生生之门』 『 云原生前置知识』 『 云原生Docker』 『 云原生Kubernetes』 『 云原生KubeSphere』 『 云原生DevOps』 &#x1f6a9;点击关注本专栏 提示&#xff1a;已经更新的或正在更新的…

自动驾驶之MultiPath++论文阅读笔记

预测道路参与者的future behavior. 摘要 将输入由dense image-based encoding改为a sparse encoding of heterogeneous scene elements. 即用polylines(折现)来描述road features和原始的agent state information(例如位置、速度和加速度)。 主要方法是对这些元素进行a conte…

【POJ No. 2778】DNA 序列 DNA Sequence

【POJ No. 2778】DNA 序列 DNA Sequence 北大OJ 题目地址 【题意】 DNA序列是一个只包含A、C、T和G的序列。分析DNA序列片段非常有用&#xff0c;若动物的DNA序列包含片段ATC&#xff0c;则意味着该动物可能患有遗传病。 给定m 个遗传病片段&#xff0c;求有多少种长度为n 的…

自动驾驶两大路线对决,渐进式玩家为何更容易得人心?

HiEV消息&#xff08;文/长海&#xff09;对自动驾驶赛道而言&#xff0c;2022年的冬天格外冷冽。寒潮袭来&#xff0c;从各家的应变方式看&#xff0c;不同路径的玩家呈现“冰火两重天”&#xff0c;进化的趋势也越来越清晰。 以Waymo为代表、持续研发L4级无人驾驶的跨越式路线…