无法将命令的输出重定向到输出fi

2024-04-30 13:00:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个python脚本来获取Mongo的dump备份。我想我的输出被重定向到一个文本文件,可以用于进一步的参考。你知道吗

我试过sys.stdout,但它只打印print命令的输出

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)

Tags: importhostifosportmongolocaldir