0

So i have been messing about on my MacOS trying to run a Terminal command from within a Python File. Below is the code which i have been using so far:

#!/usr/bin/env python3
import os
import subprocess

print("IP Configuration for Machine")
cmd = ['ifconfig']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

o, e = proc.communicate()
print('OUTPUT: ' + o.decode('ascii'))
print('ERROR: '  + e.decode('ascii'))
print('CODE: ' + str(proc.returncode))

It works perfectly fine for when i intend to run only one Terminal Command. Right now i intend to run more than one, but so far it has been giving me errors. An example of my attempt:

print("IP Configuration for Machine & List Directory")
cmd = ['ifconfig', 'ls']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

I am wondering if there is a solution to my predicament

  • `Popen` takes the name of a command and its arguments, not two separate commands to be run sequentially. You need to use `subprocess.Popen` twice, once for each element of `cmd`. – chepner May 28 '21 at 15:23

1 Answers1

0

The argument to Popen is the name of one command to execute. To run reveral, run several subprocesses (or run one which runs many, i. e. a shell).

By the by, probably avoid bare Popen if you just need to run a process and wait for it to complete.

for cmd in ['ifconfig', 'ls']:
    p = subprocess.run(cmd, capture_output=True, check=True, text=True)
    print('output:', p.stdout)
    print('error:', p.stderr)
    print('result code:', p.returncode)

or

p = subprocess.run('ifconfig; ls', shell=True, check=True, capture_output=True, text=True)
print(p.stdout, p.stderr, p.returncode)

But usually avoid a shell if you can, too.

tripleee
  • 175,061
  • 34
  • 275
  • 318