私は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'
のような奇妙な書式設定がありますか? - リストにする必要はありますか?
- 明確な文字列になるように、もう少しフォーマットする必要がありますか?
2)あなたはそれ作っ'out.split()'を実行してリストを作成します – TemporalWolf
Python 3を実行しています。すべての文字列は実際にはUnicode文字列です(各文字は2バイトです)。文字列の前の 'b'接頭辞は、文字列がバイト文字列であることを意味します(各文字は1バイトです)。これは、システムがバイトコードを返し、PythonのようにUnicodeで「ネイティブに」動作しないためです。 – Zizouz212
ああ「スプリット」は意図しない。私は気付かなかった。そこに「ストリップ」が欲しかった。 – F1sher