<分区>
尝试下面的操作,我得到一个创建为空的文件 Import_Conf_Output.txt2
,谁能告诉我哪里出了问题?
cmd1 = 'my command'
os.system(cmd1 + "1>&/home/s_admin/Import_Conf_Output.txt" + "2>&/home/s_admin/Error.txt")
标签 python
<分区>
尝试下面的操作,我得到一个创建为空的文件 Import_Conf_Output.txt2
,谁能告诉我哪里出了问题?
cmd1 = 'my command'
os.system(cmd1 + "1>&/home/s_admin/Import_Conf_Output.txt" + "2>&/home/s_admin/Error.txt")
最佳答案
如评论和 another answer 中所述,您的命令字符串缺少空格。因此,您发送到 shell 的命令是:
my command1>&/home/s_admin/Import_Conf_Output.txt2>&/home/s_admin/Error.txt
也就是说,subprocess模块旨在取代 os.system (和其他类似设备)。来自docs ,您的命令的替换将是:
subprocess.call('my command' + ' 1> /home/s_admin/Import_Conf_Output.txt 2> /home/s_admin/Error.txt', shell=True)
您可能想查看子流程模块的文档,看看是否有更好的方法来完成您正在做的事情。
编辑:要按照提供的命令行工作,还应从重定向中删除与号,因为不会合并不同的输出流。
但是,正如 gbtimmon 在评论中指出的那样,您可以在 subprocess.call 中指定 stdout 和 stderr。下面一行使用 ls
命令代替 my command
,将输出发送到 ls.out。由于没有错误,ls.err 为空。
subprocess.call('ls', stdout=open('ls.out', 'w'), stderr=open('ls.err', 'w'))
关于python - 将 os.system 输出重定向到 python 中的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42808694/