[英]How to use commands from a txt file and store Python outputs in a txt file
输入文件看起来像这样我正在尝试做以下事情,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
这是我的 function,用于读取给定文件并将命令作为字符串列表返回。 和,
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
...
我无法弄清楚如何使用我存储在“数据”中的命令并在不使用 python 内置库以外的库的情况下存储它们的结果。
`
您可以使用 subprocess 存储命令的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.