我试图在文本文件中迭代行,其中每一行都是我发送到命令行运行的命令。我想通过将每个命令及其输出放在变量中来跟踪它们,但我不确定如何为每个迭代分配一个单独的变量。这是我的代码澄清。
示例command.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.
答案 0 :(得分:2)
保存每个命令非常简单。我们所要做的就是定义我们在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:
并将所有其他代码放在该块中。
答案 1 :(得分:1)
使用列表保存输出。要将输出保存到列表,请使用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)))
答案 2 :(得分:0)
你可以按照以下方式做点什么:
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)]