redircet stdout使用变量python 3来归档

时间:2018-05-07 11:51:21

标签: python python-3.x

我想使用变量" path"将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')

2 个答案:

答案 0 :(得分:1)

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

这是一个python2.7示例,其中os.system可以执行您想要的操作

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

答案 1 :(得分:0)

这是使用subprocess.run非常最小示例。此外,搜索StackOverflow以及#34; python shell重定向",您将立即获得此结果:

Calling an external command in Python

import subprocess


def run(filename, command):
    with open(filename, 'wb') as stdout_file:
        process = subprocess.run(command, stdout=subprocess.PIPE, shell=True)
        stdout_file.write(process.stdout)
        return process.returncode

run('test_out.txt', 'ls')