Python Forum

Full Version: subprocess return of stdout after running Linux command
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I wrote a function which accepts an argument (a Linux command) and then runs subprocess.check_output

  
#!/usr/local/bin/python3.5
#
#
#  FUNCTIONS
#
def run_command(command):
    p = subprocess.check_output(command, stdin=None, stderr=None, timeout=None, shell=True, universal_newlines=False )
    print('the output value is: ')
    print(p)

#
#
#   END OF FUNCTIONS
#
import subprocess
run_command('pwd')
when invoking this function with the argument 'pwd'  I expected to get a string containing '/home/jdavis'

however, this is what I got for command output:
[jdavis@localhost ~]$ ./ex1
the output value is:
b'/home/jdavis\n'
[jdavis@localhost ~]$


Why do I get the 'b' prepended  and the '\n  at the end?  and how to I prevent this?
b is bytes. You need to convert it to a string and then remove the newline with strip method
    print(p.decode().strip())
import os

print(os.getcwd())
I would have tried that first, but saw in documentation that os  is deprecated  -  I'm running 3.5.2  -  should I be concerned about using the os command?
Where did you read this? In the Python documentation there is nothing like this.
https://docs.python.org/3/library/os.html
(Oct-13-2016, 05:06 PM)ivanachukapawn Wrote: [ -> ]saw in documentation that os  is deprecated
Link?
I found the 'deprecated' os  in multiple places (google 'Python os deprecated' .  Here is quote from Kevin London's blog:

The Command Injection Series
The first group of dangerous Python functions revolve around trusting user-provided input and piping it into a shell.
Why they’re useful
Sometimes you need to send a command-line application and it’s convenient to do that using Python’s subprocess module using
subprocess.call()
and setting
shell=True
.
os.system()
and
os.popen*()
have been deprecated since Python 2.6 in favor of the subprocess module. They have a simple API and they’ve been around for a while so you may run into them in older applications.

But I'm not particularly worried about any security concerns via os   and I found it vastly superior to subprocess in terms of simplicity and clean output returned  (apparently, subprocess returns byte output from command stdout)

So I'm going to proceed with os.  Thanks so much for the help.
The module itself is not deprecated, just specific functions within it. You can use the os module, just avoid the deprecated parts.