当前位置:   article > 正文

7、subprocess 模块:执行系统命令_subprocess.run cmd 参数

subprocess.run cmd 参数

点击上方分类专栏、进行系统性学习(文末可扫码领取资料)

  • subprocess 模块允许我们启动一个新进程,并连接到它们的输入/输出/错误管道,从而获取返回值。
  • 参考:1、subprocess · 语雀

1、subprocess.run

  • 语法格式:
  1. subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None,
  2. capture_output=False, shell=False, cwd=None, timeout=None,
  3. check=False, encoding=None, errors=None, text=None, env=None,
  4. universal_newlines=None)
  • 参数解析:
    • args:要执行的命令。必须是一个字符串或字符串参数列表
    • stdinstdoutstderr:子进程的标准输入、输出和错误。其值可以是subprocess.PIPEsubprocess.DEVNULL、一个已经存在的文件描述符、已经打开的文件对象或者 None(默认,表示什么都不做)。stderr 可以合并到 stdout 里一起输出
      • subprocess.PIPE表示为子进程创建新的管道
      • subprocess.DEVNULL表示使用os.devnull
    • timeout:设置命令超时时间。如果命令执行时间超时,子进程将被杀死,并弹出 TimeoutExpired 异常
    • check:如果该参数设置为 True,并且进程退出状态码不是 0,则弹出 CalledProcessError 异常
    • encoding:如果指定了该参数,则 stdin、stdout 和 stderr 可以接收字符串数据,并以该编码方式编码。否则只接收 bytes 类型的数据
    • shell:如果该参数为 True,将通过操作系统的 shell 执行指定的命令
  • 返回CompletedProcess实例,和直接Popen差不多,实现是一样的(实际也是调用 Popen,与 Popen 构造函数大致相同)
  • 示例:
  1. import subprocess
  2. # 执行 ``ls -l /dev/null`` 命令;
  3. # 执行后, 会在终端输出: crw-rw-rw- 1 root root 1, 3 Apr 26 2022 /dev/null
  4. res = subprocess.run(["ls", "-l", "/dev/null"])
  5. # jy: CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0)
  6. # returncode 记录执行完子进程状态, 为 0 则表明它已经运行完毕, 若值为负值 "-N", 表明
  7. # 子进程被终;
  8. print(res)
  9. def runcmd(command):
  10. ret = subprocess.run(command, shell=True,
  11. stdout=subprocess.PIPE,
  12. stderr=subprocess.PIPE,
  13. encoding="utf-8", timeout=1)
  14. if ret.returncode == 0:
  15. print("success:",ret)
  16. else:
  17. print("error:",ret)
  18. # jy: 假设当前文件夹中有两个文件: test.py 和 test.py
  19. runcmd(["ls","-a"]) # 序列参数
  20. """
  21. success: CompletedProcess(args=['ls', '-a'], returncode=0, stdout='test.py\ntest.py\n', stderr='')
  22. """
  23. runcmd("exit 1") # 字符串参数
  24. """
  25. error: CompletedProcess(args='exit 1', returncode=1, stdout='', stderr='')
  26. """

2、subprocess.Popen

  1. class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None,
  2. stderr=None, preexec_fn=None, close_fds=True, shell=False,
  3. cwd=None, env=None, universal_newlines=False,
  4. startupinfo=None, creationflags=0,restore_signals=True,
  5. start_new_session=False, pass_fds=(), *, encoding=None,
  6. errors=None)
  • 参数说明:
    • args:shell 命令,可以是字符串或者序列类型(如:list,元组)
    • bufsize:缓冲区大小。当创建标准流的管道对象时使用,默认 -1
      • 0:不使用缓冲区
      • 1:表示行缓冲,仅当universal_newlines=True时(即文本模式)可用
      • 正数:缓冲区大小
      • 负数:使用系统默认的缓冲区大小
    • stdinstdoutstderr:分别表示程序的标准输入、输出、错误句柄
    • preexec_fn:只在 Unix 平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
    • shell:是否通过操作系统的 shell 执行指定的命令
    • cwd:设置子进程的当前目录
    • env:指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承
  • 示例:创建一个子进程并执行简单命令
  1. import subprocess
  2. # 创建一个子进程并执行简单命令
  3. p = subprocess.Popen('ls -l', shell=True)
  4. #p = subprocess.Popen(['ls', '-cl'])
  5. print("-" * 66)
  6. print(p)
  7. print("-" * 66)
  8. print(p.returncode)
  9. print("-" * 66)
  10. print(p.wait())
  11. print("-" * 66)
  12. print(p.returncode)
  13. """
  14. ------------------------------------------------------------------
  15. <Popen: returncode: None args: 'ls -l'>
  16. ------------------------------------------------------------------
  17. None
  18. ------------------------------------------------------------------
  19. total 4
  20. -rw-r--r-- 1 root root 192 Feb 1 10:09 test.py
  21. -rw-r--r-- 1 root root 0 Feb 1 08:19 tmpFile
  22. 0
  23. ------------------------------------------------------------------
  24. 0
  25. """

Popen 对象方法

  • poll():检查进程是否终止,如果终止返回 returncode,否则返回 None
  • wait(timeout):等待子进程终止
  • communicate(input, timeout):和子进程交互,发送和读取数据
  • send_signal(singnal):发送信号到子进程
  • terminate():停止子进程(发送SIGTERM信号到子进程)
  • kill():杀死子进程(发送SIGKILL信号到子进程)
  • 示例:
  1. import time
  2. import subprocess
  3. def cmd(command):
  4. subp = subprocess.Popen(command, shell=True,
  5. stdout=subprocess.PIPE,
  6. stderr=subprocess.PIPE,
  7. encoding="utf-8")
  8. subp.wait(2)
  9. if subp.poll() == 0:
  10. print(subp)
  11. print(subp.communicate())
  12. else:
  13. print("失败")
  14. cmd("perl -v")
  15. """
  16. <Popen: returncode: 0 args: 'perl -v'>
  17. ('\nThis is perl 5, version 26, subversion 3 (v5.26.3) built for x86_64-linux-thread-multi\n(with 55 registered patches, see perl -V for more detail)\n\nCopyright 1987-2018, Larry Wall\n\nPerl may be copied only under the terms of either the Artistic License or the\nGNU General Public License, which may be found in the Perl 5 source kit.\n\nComplete documentation for Perl, including FAQ lists, should be found on\nthis system using "man perl" or "perldoc perl". If you have access to the\nInternet, point your browser at http://www.perl.org/, the Perl Home Page.\n\n', '')
  18. """
  19. cmd("exit 1")
  20. """
  21. 失败
  22. """

3、subprocess.check_output

  • subprocess.check_output函数可以执行一条 shell 命令,并返回命令的输出内容(Run command with arguments and return its output.)。
  1. subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None,
  2. encoding=None, errors=None, universal_newlines=None,
  3. timeout=None, text=None, **other_popen_kwargs)
  • If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.
  • This is equivalent to:
    • run(..., check=True, stdout=PIPE).stdout
  • 示例:
  1. import subprocess
  2. # jy: 默认返回结果为 bytes 形式;
  3. output = subprocess.check_output(["ls", "-a"], shell = False)
  4. # jy: b'.\n..\ntest.py\n'
  5. print(output)
  6. # jy: <class 'bytes'>
  7. print(type(output))
  8. # jy: 设置编码, 使得输出结果为字符串形式;
  9. output = subprocess.check_output(["ls", "-a"], shell = False, encoding="utf8")
  10. #output = subprocess.check_output(["ls", "-a"], shell = False, encoding="UTF-8")
  11. # jy: '.\n..\ntest.py\n', 输出时会被换行输出如下:
  12. """
  13. .
  14. ..
  15. test.py
  16. """
  17. print(output)
  18. # jy: <class 'str'>
  19. print(type(output))
  20. # jy: ['.', '..', 'test.py', '']
  21. print(output.split("\n"))
  • By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level.

融码一生:专注 Python、Linux、C/C++、机器学习 & 深度学习 & NLP 领域创作

下方扫码关注公众号,获取完整 PDF / 线上电子书

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/731139?site
推荐阅读
相关标签
  

闽ICP备14008679号