简体   繁体   English

将os.system输出重定向到python中的文本文件

[英]Redirecting os.system output to a text file in python

Trying the below I get a file Import_Conf_Output.txt2 created as empty, can anyone tell me what is wrong? 尝试以下我得到一个文件Import_Conf_Output.txt2创建为空,谁能告诉我有什么问题?

cmd1 = 'my command'
os.system(cmd1 + "1>&/home/s_admin/Import_Conf_Output.txt" + "2>&/home/s_admin/Error.txt")

your should call as: 你应该打电话给:

cmd1 = 'my command'
os.system(cmd1 + " 1>/home/s_admin/Import_Conf_Output.txt" + " 2>/home/s_admin/Error.txt")

As noted in a comment and another answer , your command string is missing spaces. 正如评论和另一个答案所述 ,您的命令字符串缺少空格。 Thus the command you are sending to the shell is: 因此,您发送给shell的命令是:

my command1>&/home/s_admin/Import_Conf_Output.txt2>&/home/s_admin/Error.txt

That said, the subprocess module is meant to replace os.system (and other similar devices). 也就是说, 进程模块旨在取代os.system(和其他类似设备)。 From the docs , the replacement for your command would be: 文档中 ,替换您的命令将是:

subprocess.call('my command' + ' 1> /home/s_admin/Import_Conf_Output.txt 2> /home/s_admin/Error.txt', shell=True)

You may want to look through the subprocess module's documentation to see if there is a better way to accomplish what you are doing. 您可能希望查看子进程模块的文档,看看是否有更好的方法来完成您正在做的事情。

Edit: To work given the command line as provided, the ampersands also should be removed from the redirection, as the different output streams are not going to be combined. 编辑:为了在给定命令行的情况下工作,还应该从重定向中删除&符号,因为不会组合不同的输出流。

However, as gbtimmon noted in a comment, you can specify stdout and stderr in subprocess.call. 但是,正如gbtimmon在注释中指出的那样,您可以在subprocess.call中指定stdout和stderr。 The following line, using the ls command in place of my command , sent the output to ls.out. 以下行使用ls命令代替my command ,将输出发送到ls.out。 Since there was no error, ls.err was empty. 由于没有错误,ls.err为空。

subprocess.call('ls', stdout=open('ls.out', 'w'), stderr=open('ls.err', 'w'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM