python - 无法将命令的输出重定向到输出文件

标签 python python-3.x mongodb

我正在编写一个 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/

相关文章:

javascript - 'book' 已定义但从未使用 MEAN 堆栈 Controller

json - 严格模式下的MongoDB日期格式

python - django配置不正确的错误

python - 移动 pandas 数据框上的整列

python - 将对象转换为 pandas 中的 float 对象并替换 $ 符号

django - 当我不访问它时出现错误 serializer.data

python - 如何以给定格式 "clean-up"字符串数据以便可以从中创建字典?

python - 如何在python脚本中使用upsertField或upsert参数导入mongo集合中的json数据

python - 编辑 Ctypes 结构的缓冲区

python - 同时显示文字和播放音频