我正在编写一个 python 脚本来对 Mongo 进行转储备份。我希望我的输出重定向到可用于进一步引用的文本文件。
我尝试过sys.stdout
,但它只是打印打印命令的输出
sys.stdout
!/usr/bin/python3
import os
import time
import datetime
import sys
import subprocess
import glob
'''
mongo backup by python
'''
BKP_DIR = "/apps/mongobackup/mongo_backup"
BLD = "/apps/mongobackup/logs"
# configs:
host = "NA" # if host is your local machine leave it NA
db_name = sys.argv[1]
port = sys.argv[2] # if mongo is on default port (37017) leave in NA
now = datetime.datetime.now()
new_today_date = now.strftime("%m%d%Y_%H%M%S")
outputs_dir = os.path.join(BKP_DIR, db_name, new_today_date)
output_log=os.path.join(BLD,"output.log")
try:
# Create target Directory
os.mkdir(outputs_dir)
print("Directory " , outputs_dir , " Created ")
except FileExistsError:
print("Directory " , outputs_dir , " already exists")
username = "dba" # if there is no username set, leave it in NA
password = "dba" # if there is no password set, leave it in NA
def render_output_locations():
return outputs_dir + time.strftime("%m%d%Y_%H%M%S")
orig_stdout = sys.stdout
f = open('out.txt', 'w')
sys.stdout = f
def run_backup():
command = "mongodump"
if host != 'NA':
command += " --host " + host
if port != 'NA':
command += " --port " + port
if username != 'NA':
command += " --username " + username
if password != 'NA':
command += " --password " + password
if db_name != 'NA':
command += " -d local --authenticationDatabase admin"
command += " --out " + outputs_dir
os.system(command)
print("mongo backup progress started")
run_backup()
sys.stdout = orig_stdout
f.close()
输出:-
$a>cat out.txt
mongo备份进度已开始
所需输出:-
$>cat out.txt
mongo备份进度已开始
2019-08-20T03:33:03.132-0400 writing local.oplog.rs to
2019-08-20T03:33:03.132-0400 writing local.startup_log to
2019-08-20T03:33:03.132-0400 writing local.replset.minvalid to
2019-08-20T03:33:03.132-0400 writing local.replset.election to
2019-08-20T03:33:03.184-0400 done dumping local.startup_log (1 document)
2019-08-20T03:33:03.184-0400 writing local.replset.oplogTruncateAfterPoint to
2019-08-20T03:33:03.184-0400 done dumping local.replset.election (1 document)
2019-08-20T03:33:03.208-0400 done dumping local.replset.minvalid (1 document)
2019-08-20T03:33:03.209-0400 done dumping local.replset.oplogTruncateAfterPoint (1 document)
2019-08-20T03:33:05.833-0400 local.oplog.rs 1881559
2019-08-20T03:33:06.509-0400 local.oplog.rs 2389014
2019-08-20T03:33:06.509-0400 done dumping local.oplog.rs (2389014 documents)
最佳答案
使用subprocess.call
而不是os.system
:
from subprocess import call
output = open('output.txt', 'w')
call(command, stdout=output, stderr=output, shell=True)
关于python - 无法将命令的输出重定向到输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57568911/