首页 > 解决方案 > 使用变量python 3将标准输出重定向到文件

问题描述

我想使用变量“路径”将 shell 命令的 o/p 重定向到文件,但它不起作用

import os, socket, shutil, subprocess
host = os.popen("hostname -s").read().strip()
path = "/root/" + host

if os.path.exists(path):
  print(path, "Already exists")
else:
   os.mkdir("Directory", path , "Created")

os.system("uname -a" > path/'uname')  # I want to redirect o/p of shell commands to file using varibale "path" but it is not working 
os.system("df -hP"> path/'df')

标签: pythonpython-3.x

解决方案


我认为问题在于 os.system 命令中的裸 > 和 / 符号...

这是一个带有 os.system 的 python2.7 示例,它可以满足您的需求

import os
path="./test_dir"
command_str="uname -a > {}/uname".format(path)
os.system(command_str)

推荐阅读