zoukankan      html  css  js  c++  java
  • subprocess使用,进入到某个目录下执行shell命令

    subprocess是用来fork一个子进程的。这个子进程可以运行一个外部程序。

    函数:

    • subprocess.call()
    • subprocess.check_output()
    • subprocess.check_call()

    这三个函数都调用Popen函数:因此Popen类的初始化函数的入参,都可以通过被上面三个函数使用

    def check_output(*popenargs, **kwargs):
    r"""Run command with arguments and return its output as a byte string.

    If the exit code was non-zero it raises a CalledProcessError. The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.

    The arguments are the same as for the Popen constructor. Example:

    >>> check_output(["ls", "-l", "/dev/null"])
    'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null '

    The stdout argument is not allowed as it is used internally.
    To capture standard error in the result, use stderr=STDOUT.

    >>> check_output(["/bin/sh", "-c",
    ... "ls -l non_existent_file ; exit 0"],
    ... stderr=STDOUT)
    'ls: non_existent_file: No such file or directory '
    """
    if 'stdout' in kwargs:
    raise ValueError('stdout argument not allowed, it will be overridden.')
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
    class Popen(object):
    _child_created = False # Set here since __del__ checks it

    def __init__(self, args, bufsize=0, executable=None,
    stdin=None, stdout=None, stderr=None,
    preexec_fn=None, close_fds=False, shell=False,
    cwd=None, env=None, universal_newlines=False,
    startupinfo=None, creationflags=0):

    举例:app_module_list = subprocess.check_output("grep '[INFO] cn.tong' dependency.log | awk '{print $2}' | awk -F':' '{print $2}'", shell=True, cwd=dir)

    进入到目录dir后执行shell命令:grep '[INFO] cn.tong' dependency.log | awk '{print $2}' | awk -F':' '{print $2}',标准输出stdout赋值给app_module_list

    参考:https://blog.csdn.net/bitcarmanlee/article/details/51622263

  • 相关阅读:
    vue之实现日历----显示农历,滚动日历监听年月改变
    vue填坑之全局引入less,scss,styl文件
    vue填坑之引入iconfont字体图标
    纯JS实现带小圆点缩略图及左右箭头的轮播图
    canvas绘制时钟
    CSS实现鼠标移入图片边框有小三角
    jquery之.outerWidth()
    CSS ::selection 选中文字效果
    LINUX下用Nginx和Node.js构建一个简单的项目(4)
    LINUX下用Nginx和Node.js构建一个简单的项目(3)
  • 原文地址:https://www.cnblogs.com/shengulong/p/9643166.html
Copyright © 2011-2022 走看看