如何为每个for循环迭代分配变量

2024-10-16 20:53:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图迭代文本文件中的行,其中每一行都是我发送给命令行运行的命令。我想通过将它们放入变量中来跟踪每个命令及其输出,但我不确定如何为每个迭代分配单独的变量。下面是我要澄清的代码。你知道吗

示例命令.txt文件:

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

逐行读取和运行命令的代码

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...)

我想这样做的原因是,我可以创建一个命令日志文件,其中将说明给定的命令和输出。日志文件如下所示:

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.

Tags: 文件theto代码命令echotxthello
3条回答

你可以按照这些思路做一些事情:

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)) 

如果要将其保存在列表中:

with open(fn) as f:
    list_o_cmds=[(line,subprocess.check_output(line, shell=True)) 
                          for line in (e.rstrip() for e in f)]       

保存每个命令非常简单。我们所要做的就是定义在for循环之外保存命令的位置。例如,我们可以创建一个空列表,并在每次迭代期间附加到该列表。你知道吗

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

为了保存输出,请参见this question,并在for循环之外使用另一个列表。你知道吗

另外,您应该使用

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

把你的其他代码都放在那个块里。你知道吗

使用列表保存输出。要将输出保存到列表中,请使用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)))

相关问题 更多 >