2017-02-14 2 views
0

私は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__'] 
  1. なぜ私の質問があります各ファイルの前にb'のような奇妙な書式設定がありますか?
  2. リストにする必要はありますか?
  3. 明確な文字列になるように、もう少しフォーマットする必要がありますか?
+1

2)あなたはそれ作っ'out.split()'を実行してリストを作成します – TemporalWolf

+0

Python 3を実行しています。すべての文字列は実際にはUnicode文字列です(各文字は2バイトです)。文字列の前の 'b'接頭辞は、文字列がバイト文字列であることを意味します(各文字は1バイトです)。これは、システムがバイトコードを返し、PythonのようにUnicodeで「ネイティブに」動作しないためです。 – Zizouz212

+0

ああ「スプリット」は意図しない。私は気付かなかった。そこに「ストリップ」が欲しかった。 – F1sher

答えて

0

出力をデコードして、バイト文字列を「通常の」テキストに変換します。以下を検討し、より明確な答えを提供するために

out = execute_shell(command).decode("utf-8") 
print(" ".join(out.split())) 
0

:リストはsplitによって作成され、あなたは、通常のls出力を作成するために、空白文字でリストをjoinでき

1)の出力あなたのプロセスはASCII形式ではないので、ファイルの先頭に表示されるのは文字列がバイナリ形式であることを示しています。

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 
関連する問題