文章目录

  • 前言
  • 正文
  • 小结
  • 参考文献

前言

创作开始时间:2021年4月2日10:07:30

如题。不多比比了,赶时间,直接上代码(算是目前用的比较顺手的一个版本了)。

正文

import subprocess
import logging
import re# ======================================= refer to: https://www.askpython.com/python-modules/python-system-command
def run_cmd_with_output(cmd, logger = None):"""run cmd and print output.refer to : https://stackoverflow.com/questions/40222793/python-subprocess-check-output-stderr-usage"""# shell=True是为了让cmd为string(而非list,我更喜欢用string)的时候能正常执行p = subprocess.run(cmd, shell=True, stdout = subprocess.PIPE, stderr=subprocess.PIPE)# 一定要decode,不然output的type会是bytes!output = p.stdout.decode('utf-8')# 获取stderr!error = p.stderr.decode('utf-8')return output# 不输出output的,还是挺简单的。一行代码搞定
def run_cmd_without_output(cmd, logger = None):if logger:logger.info(f"cmd: {cmd}")res = subprocess.call(cmd, shell = True)

另,还有个老版本,在此列出以供参考:

# 下面这个,其实还是挺好用,但是不能得到stderr,遂弃之
# def run_cmd_with_output_old(cmd, logger = None):
#     """
#     run cmd and print output.
#     But the subprocess.check_output cannot get stderr.
#     So I'd like to create a new method according to : https://stackoverflow.com/questions/40222793/python-subprocess-check-output-stderr-usage
#     Quote:
#     >subprocess.check_output will raise the exception you see if there's a non-zero exit code. It sound like what you're trying to get is a simple way of reading STDERR, which in that case the easiest thing is to use subprocess.run and pipe STDOUT and STDERR
#     """
#     if logger:
#         logger.info(f"cmd: {cmd}")#     # if re.search(f"java {JAVA_ARGS} -cp(.*)gumtree", cmd, re.I | re.DOTALL):
#     #     print("debug here.")#     # command = "pip install pymysql" #command to be executed
#     res = subprocess.check_output(cmd, shell = True) #, stderr= subprocess.STDOUT
#     output = res.decode('utf-8')#     # if logger:
#     #     # too large
#     #     #logger.info(f"Output (Decoded string): {output}") #decoded result
#     # else:
#     #     # print("Return type: ", type(res)) #type of the value returned
#     #     print("Decoded string: ", output) #decoded result#     return output

小结

以上。

创作结束时间:2021年4月2日10:16:15

参考文献

有很多,但都没记下来,现在代码已成,(暂)不要参考文献也罢。

【已解决】如何用Python执行终端命令cmd(使用suprocess.run,并获取到stderror)相关推荐

  1. Python 执行终端命令

    Python执行终端命令有多种方法. 方法一 使用示例: import os os.system('ls') 该方法无法输出命令执行结果 方法二 使用示例: import os res = os.po ...

  2. python write 写多行_如何用 Python 执行单行命令

    一般来说,面对日常处理的一些小任务,直接用 sed,grep 之类的就可以搞定,更复杂一点的就会考虑 awk 或者用一些现成的轮子,要是 awk 搞不定我就只好用 Python 了.但有些时候,我仅仅 ...

  3. Python 执行 shell命令 的几个方法小结

    参考:https://blog.csdn.net/ronnyjiang/article/details/53333538 Python 执行 shell 命令 Python 可以执行 shell 命令 ...

  4. python执行shell命令行_python执行命令行:python中执行shell命令行read结果

    +++++++++++++++++++++++++++++ python执行shell命令 1 os.system  (只有这个方法是边执行边输出,其他方法是最后一次性输出) 可以返回运行shell命 ...

  5. python2没有pip命令_解决Windows下python和pip命令无法使用的问题

    一. python命令找不到 安装python之后经常会出现下面的问题 , python命令找不到,这是因为Windows的环境变量中没有定义python的安装路径 这个时候我们先找到python的安 ...

  6. [转载] python执行shell命令的几种方法

    参考链接: 使用Python执行Shell命令 目前我使用到的python中执行cmd的方式有三种: 1. 使用os.system("cmd") 这是最简单的一种方法,特点是执行的 ...

  7. python怎样执行curl命令_如何使用python执行curl命令

    如何使用python执行curl命令 我想在python中执行curl命令. 通常,我只需要在终端输入命令并按回车键. 但是,我不知道它在python中是如何工作的. 该命令如下所示: curl -d ...

  8. 用Python执行Linux命令

    用Python执行Linux命令 直接上代码: import os # 导入os模块cmd1 = 'ls' # 要执行的Linux命令放入单引号中(用于情况 1) cmd2 = 'systemctl ...

  9. python执行linux命令返回结果_python执行linux命令的简单示例

    对python执行linux命令的两种方法感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧! python执行linux命令有两种方法: 在此以Linux常用的ls命令为例: ...

最新文章

  1. java int 0.5_java int转float精度缺失原因?
  2. LISTVIEW嵌套GRIDVIEW的一些处理(点击GRIDVIEW的条目,能够显示他在LISTVIEW中的位置)(对这篇文章的优化处理,不每次都new onItemClickListener)...
  3. LeCun之后Jeff Dean离奇躺枪,哥大黑人女博士:你们得引用我!
  4. mysql 常用sql语句 简介
  5. MD5数据加密于文件加密
  6. VS2017文件操作之使用fopen函数总结
  7. 现在相亲还要体检报告了?
  8. 通用数据库管理工具_了解为什么这个直观的工具是您团队的通用团队管理工具...
  9. 以后再想大数据杀熟就没那么容易了
  10. 引用类型和原始类型的对比(java)
  11. 51nod1464(trie + dfs)
  12. GdiPlus[15]: IGPLinearGradientBrush 之 GammaCorrection
  13. 矩阵分析 (八) 矩阵的直积
  14. 百度开源的71款项目
  15. 软件测试必读的经典书籍
  16. Transmission 下载列表、下载文件 迁移机器指南
  17. 【方差分析】之matlab求解
  18. python语言程序设计袁方答案_北邮“爱课堂”教学平台
  19. 2017-2018-2 20179215《网络攻防实践》第二周作业
  20. mysql的join查询和多次查询比较

热门文章

  1. 时隔3年,再次折腾BlackBerry 8830!
  2. mongrel服务器
  3. Clamav杀毒安装配置手册
  4. 如何使用金山文档进行同一文档的团队协作
  5. 终于解决 ERROR 1044(42000): Access denied for user ''@'localhost' to database,亲测有效
  6. python对excel求和_Python 两个Excel文件对应位置求和并存储
  7. Linux kernel oops
  8. 混合云架构中的数据加密
  9. android java json_探究Android系统中解析JSON数据的方式
  10. 附加数据库 对于服务器 XXX失败