输入文件如下所示我想要做的是,1)从txt文件中获取shell命令2)将这些命令的输出存储在另一个txt文件中。
但是我不知道如何使用和存储这些命令。
import os
def read_file(file_name): #file_name must be a string
current_dir_path = os.getcwd() #getting current directory path
reading_file_name = file_name
reading_file_path = os.path.join(current_dir_path, reading_file_name) #file path to read
# Open file
with open(reading_file_path, "r") as f: #"r" for reading
data = f.readlines()
for i in range(len(data)):
data[i] = data[i].replace("n", "")
return data
这是我的函数读取给定的文件,并返回命令作为字符串列表。,
outputs = "?"
def write_file(file_name): #file_name must be a string
current_dir_path = os.getcwd()
writing_file_name = file_name
writing_file_path = os.path.join(current_dir_path, writing_file_name)
# Open file and add
with open(writing_file_path, "w") as f:
f.write(outputs)
我创建了几个函数。输入文件包含以下行:
func1 val1 val2 val3
func3 valx valy valz
func2 val
...
我不知道如何使用我存储在'data'中的命令,并且不使用python内置库以外的库来存储它们的结果。
可以使用subprocess
存储命令的输出。您可以尝试以下操作:
from subprocess import Popen, PIPE
def write_file(command):
proc = Popen(command, shell=True, stdin=PIPE, stdout=PIPE,
stderr=PIPE)
ret = proc.stdout.readlines()
output = [i.decode('utf-8') for i in ret]
result = output[0]
with open('output.txt', 'a') as file:
file.write(result)
file.close()
#usage example
write_file('echo hi')
#'hi' will be written in output.txt