0

I am new to Python. There is my question:

a) ShellHelper.py:

import subprocess


def execute_shell(shell):
    process = subprocess.Popen(shell, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output = process.communicate()[0]
    exit_code = process.returncode

    if exit_code == 0:
        return output
    else:
        raise Exception(shell, exit_code, output)

b) Launcher.py

from ShellHelper import *


command = input("Enter shell command: ")
out = execute_shell(command)
print(out.split())

c) My terminal:

pc19:AutomationTestSuperviser F1sherKK$ python3 Launcher.py 
Enter shell command: ls
[b'Launcher.py', b'ShellHelper.py', b'__pycache__']
  1. Why do I get this weird formatting like b' before each file?
  2. Does it have to be list?
  3. Do I need to some more formatting so it is a clear String?
wallyk
  • 56,922
  • 16
  • 83
  • 148
F1sher
  • 7,140
  • 11
  • 48
  • 85
  • 1
    2) You made it a list by doing `out.split()` – TemporalWolf Feb 14 '17 at 23:53
  • You're running Python 3, where all strings are actually unicode strings (each char is 2 bytes). The 'b' prefix in front of the string means that the string is a byte string (each char is 1 byte). That's because the system returns a bytestring, and it doesn't operate "natively" in unicode the way python does. – Zizouz212 Feb 14 '17 at 23:56
  • Oh `split` was unintended. I didn't notice. I wanted `strip` there. – F1sher Feb 15 '17 at 00:09

2 Answers2

0

Decode the output to convert from a byte string to "regular" text. The list is created by split, you can join the lists with a space characters to create the normal ls output:

out = execute_shell(command).decode("utf-8")
print(" ".join(out.split()))
Harald Nordgren
  • 11,693
  • 6
  • 41
  • 65
0

To provide a more clear answer, consider the following:

1) The output of your process is not ASCII formatted, so the b you see at the start of your files is indicating you that the string is in binary format.

2) You are choosing to return a list to the print function like this:

'file1 file2 file3'.split() => ['file1', 'file2', 'file3']

while this would print each line in a separate line:

for foo in 'file1 file2 file3'.split():
  print foo # this will also remove the b and print the ascii alone
patito
  • 530
  • 2
  • 13