2017-09-06 17 views
-1

私は、各行が実行するコマンドラインに送るコマンドであるテキストファイルの行を繰り返そうとしています。私は各コマンドを追跡して、それらを変数に入れて出力しますが、私はどのように各反復に別々の変数を割り当てるかはわかりません。ここで明確にするために私のコードです。各ループの繰り返しに変数を割り当てる方法

例command.txtファイル:私はこれをしたい理由は、私が作成することができているライン

file = open("/home/user/Desktop" + "commands.txt", "r+") 
lines = file.readlines() 

for x in range(0,len(lines)): 
    lines[x].strip() 
    os.system(lines[x]) 
    # here I want to save each command to a different variable. 
    # (for ex.) command_x = lines[x] (so you get command_1 = echo "hello world", and so on) 
    # here I want to save the output of each command to a different variable. 
    # (for ex.) output_x = (however I access the output...) 

でコマンドラインを読み、実行するための

echo "hello world" 
echo "I am here" 
ls 

コード与えられたコマンドと出力を示すコマンドログファイル。ログファイルは次のようになります。

Time/Date 

command: echo "hello world" 
output: hello world 

command: echo "I am here" 
output: I am here 

command: ls 
output: ... you get the point. 
+0

リストを使用して追加します。 –

+0

** ** do not ** 'lines = file.readlines();を実行しないでください。範囲内のx(0、len(lines)): '' Do ** do: 'for file in:' 'with'を使ってファイルを開きます。 – dawg

+0

@ Spencerもう少し情報を得ることができます... – BBEng

答えて

2

各コマンドの保存は非常に簡単です。私たちがしなければならないことは、forループの外側にコマンドを保存する場所を定義することだけです。たとえば、空のリストを作成し、各反復中に追加することができます。 、出力を保存this questionを参照し、forループの外に別のリストを使用するためには

commands = [] 
for x in range(0,len(lines)): 
    lines[x].strip() 
    os.system(lines[x]) 
    commands.append(lines[x]) 

また、あなたは

with open("/home/user/Desktop" + "commands.txt", "r+") as f: 

を使用してファイルを読み込み、そのブロック内の他のすべてのコードを配置する必要があります。

1

出力を保存するには、リストを使用します。あなたの場合は

import subprocess   
with open(fn) as f: 
    for line in f: 
     line=line.rstrip() 
     # you can write directly to the log file: 
     print "command: {}\noutput: {}".format(line, 
         subprocess.check_output(line, shell=True)) 

:リストに出力を保存するには、subprocess.check_output使用:タプルとして

with open("/home/user/Desktop/commands.txt") as lines: 
    output = [] 
    for line in lines: 
     output.append(subprocess.check_output(line.strip(), shell=True)) 

またはコマンドを使用してを:

with open("/home/user/Desktop/commands.txt") as lines: 
    output = [] 
    for line in lines: 
     line = line.strip() 
     output.append((line, subprocess.check_output(line, shell=True))) 
+0

私はちょうどコマンドの出力とともに 'dict'または' tuple'のいずれかでコマンドを保存すると良いと言いました – MrJLP

0

あなたはこれらの線に沿って何かを行うことができます代わりにリストに保存してください:

with open(fn) as f: 
    list_o_cmds=[(line,subprocess.check_output(line, shell=True)) 
          for line in (e.rstrip() for e in f)]  
関連する問題