Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
exec_external
#1
"""#!/c/Anaconda2/Scripts/python"""
"""
Create a function called exec_external, taking a single string argument,
representing a Linux shell command to be ran.

The function must:
  1. Execute the shell command, as if it was done on the console command line
  2. The stdout/stderr outputs of the shell command should go to stdout/stderr
     of the Python program that calls the function.
  3. Return True if the execution was successful (returncode 0), False otherwise
  4. Have the following documentation:
    Execute an external shell command showing its output on stdout

For example:

  exec_external('echo foo') -> True
  # Console output # foo

  exec_external('cat nonexisting.file') -> False
  # Console output # cat: nonexisting.file: No such file or directory
"""

import subprocess
from subprocess import Popen
import os

def exec_external(arg):
    """Execute an external shell command showing its output on stdout"""
    """ar = list(arg)"""
    proc = Popen(arg)
    proc.wait()
    n = proc.returncode
    if ( n == 0 ):
        print ("-> True\n  # Console output #")
    else:
        print ("-> False\n # Console output #")
arg = 'echo foo'
"""arg = 'cat fo.txt'"""
exec_external(arg)
This is printing the following output...
$ python exec_external.py
foo
-> True
  # Console output #
I want just this output...
$ python exec_external.py
-> True
  # Console output #foo
Isnt there something similar to '$?' in bash in python, if so what is it.
Reply
#2
Do you? The example says that for that example, the console output would be "foo". Seems like you did this one nicely :)

Also, thank you for not using *args :P
Reply
#3
my outputs need to be interchanged... how to do this...
Reply
#4
Oh, I get it.  You still want the console output, but you want it AFTER you print out that it was successful.

Probably the easiest and best way would be to use subprocess.PIPE since you're already using subprocess.  
>>> import subprocess
>>> proc = subprocess.Popen("python -V", stdout=subprocess.PIPE)
>>> errors = proc.wait()
>>> print("not successful" if errors else "success!")
success!
>>> print('\n'.join(line.decode().strip() for line in proc.stdout.readlines()))
Python 3.5.2
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020