python的subprocess模块执行shell命令

subprocess模块可以允许我们执行shell命令

一般来说,使用run()方法就可以满足大部分情况

  1. 使用run执行shell命令
    In [5]: subprocess.run('echo "hello"',shell=True)
    hello
    Out[5]: CompletedProcess(args='echo "hello"', returncode=0)
  2. run方法执行的命令都是在子shell中进行的
    # shell.py的内容
    import
    subprocess subprocess.run('cd /',shell=True)

    当我们执行python shell.py时,并不会进入根目录

  3. 在特定目录下执行run方法,给run方法传入cwd参数
    subprocess.run('ls',shell=True,cwd='/')

    这条命令会在根目录下执行

原文地址:https://www.cnblogs.com/time-read/p/8306378.html