What Is The Multiplatform Alternative To Subprocess.getstatusoutput (older Commands.setstatusoutput() From Python?
The code below is outdated in Python 3.0 by being replaced by subprocess.getstatusoutput(). import commands (ret, out) = commands.getstatusoutput('some command') print ret print o
Solution 1:
I wouldn't really consider this multiplatform, but you can use subprocess.Popen
:
import subprocess
pipe = subprocess.Popen('dir', stdout=subprocess.PIPE, shell=True, universal_newlines=True)
output = pipe.stdout.readlines()
sts = pipe.wait()
print sts
printoutput
Here's a drop-in replacement for getstatusoutput
:
defgetstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell.""""""This new implementation should work on all platforms."""import subprocess
pipe = subprocess.Popen(cmd, shell=True, universal_newlines=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = str.join("", pipe.stdout.readlines())
sts = pipe.wait()
if sts isNone:
sts = 0return sts, output
This snippet was proposed by the original poster. I made some changes since getstatusoutput
duplicates stderr
onto stdout
.
The problem is that dir
isn't really a multiplatform call but subprocess.Popen
allows you to execute shell commands on any platform. I would steer clear of using shell commands unless you absolutely need to. Investigate the contents of the os
, os.path
, and shutil
packages instead.
import os
import os.pathfor rel_name inos.listdir(os.curdir):
abs_name = os.path.join(os.curdir, rel_name)
ifos.path.isdir(abs_name):
print('DIR: ' + rel_name)
elif os.path.isfile(abs_name):
print('FILE: ' + rel_name)
else:
print('UNK? ' + rel_name)
Post a Comment for "What Is The Multiplatform Alternative To Subprocess.getstatusoutput (older Commands.setstatusoutput() From Python?"