我试图迭代文本文件中的行,其中每一行都是我发送给命令行运行的命令。我想通过将它们放入变量中来跟踪每个命令及其输出,但我不确定如何为每个迭代分配单独的变量。下面是我要澄清的代码。你知道吗
示例命令.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.
你可以按照这些思路做一些事情:
如果要将其保存在列表中:
保存每个命令非常简单。我们所要做的就是定义在for循环之外保存命令的位置。例如,我们可以创建一个空列表,并在每次迭代期间附加到该列表。你知道吗
为了保存输出,请参见this question,并在for循环之外使用另一个列表。你知道吗
另外,您应该使用
把你的其他代码都放在那个块里。你知道吗
使用列表保存输出。要将输出保存到列表中,请使用
subprocess.check_output
:或将命令作为元组:
相关问题 更多 >
编程相关推荐