【问题标题】:how to run a list of bash commands with subprocess如何使用子进程运行 bash 命令列表
【发布时间】:2021-05-20 09:59:12
【问题描述】:

代码示例:


import subprocess

cmd_list = ["ls -la", "touch a.txt", "hostname"]

for _,i in enumerate(cmd_list):
    x = subprocess.run(i)
    print(x)
    print(x.args)
    print(x.returncode)
    print(x.stdout)
    print(x.stderr)

主机名按预期工作,但 ls -la 不能

预期输出: ls -la、touch 和主机名的输出

遇到错误:

  File "linux_cmd.py", line 8, in <module>
    x = subprocess.run(i)
  File "/usr/lib64/python3.6/subprocess.py", line 423, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib64/python3.6/subprocess.py", line 729, in __init__
    restore_signals, start_new_session)
  File "/usr/lib64/python3.6/subprocess.py", line 1364, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'ls -la': 'ls -la'```

【问题讨论】:

    标签: python-3.x list for-loop


    【解决方案1】:

    subprocess.run() 在您提供多个参数时要求将参数作为一个列表。

    当您想提供多个参数时,将cmd_list 更改为列表列表:

    cmd_list = [["ls", "-la"], ["touch", "a.txt"], "hostname"]

    https://docs.python.org/3/library/subprocess.html#subprocess.run

    【讨论】:

      猜你喜欢
      • 2020-07-25
      • 2013-07-18
      • 2020-05-20
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 2011-11-25
      • 2021-12-07
      相关资源
      最近更新 更多