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
The argument to Popen
is the name of one command to execute. To run reveral, run several subprocesses (or run one which runs many, ie 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.