我是Python新手。有我的问题:
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)我的终端:
pc19:AutomationTestSuperviser F1sherKK$ python3 Launcher.py
Enter shell command: ls
[b'Launcher.py', b'ShellHelper.py', b'__pycache__']
b'
这样奇怪的格式? 答案 0 :(得分:0)
将输出解码为从字节字符串转换为"常规"文本。该列表由split
创建,您可以join
带有空格字符的列表来创建正常的ls
输出:
out = execute_shell(command).decode("utf-8")
print(" ".join(out.split()))
答案 1 :(得分:0)
要提供更清晰的答案,请考虑以下事项:
1)您的进程输出不是ASCII格式的,因此您在文件开头看到的b表示该字符串是二进制格式。
2)您选择将列表返回到打印功能,如下所示:
'file1 file2 file3'.split() => ['file1', 'file2', 'file3']
虽然这会在单独的一行中打印每一行:
for foo in 'file1 file2 file3'.split():
print foo # this will also remove the b and print the ascii alone