Billie Eilish
Billie Eilish

Reputation: 17

how to run a list of bash commands with subprocess

code example:


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)

hostname works as expected but ls -la not

expected output: output of ls -la, touch and hostname

error hitted:

  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'```

Upvotes: 0

Views: 491

Answers (1)

Tzane
Tzane

Reputation: 3472

subprocess.run() expects the arguments as a list when you give more than one argument.

Change you cmd_list to a list of lists when you want to give multiple arguments:

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

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

Upvotes: 1

Related Questions