简体   繁体   English

Python subprocess.call函数不重定向输出

[英]Python subprocess.call function does not redirect output

I am trying to run a shell script called nn.sh (which constantly runs a Linux command over time), from within a python file. 我试图在python文件中运行一个名为nn.sh的shell脚本(它会随着时间的推移不断运行Linux命令)。 I am using the following piece of code: 我使用以下代码:

from subprocess import call, Popen, PIPE
call(['/bin/sh', 'nn.sh', '172.20.125.44', '10', '>>', 'log.txt'])

This code is supposed to run nn.sh with inputs 172.20.125.44 and 10 and stores the result in the file log.txt . 该代码应该使用输入172.20.125.4410运行nn.sh ,并将结果存储在文件log.txt When I run this Python script, it only shows the results of running nn.sh on the screen and it does not save them in the fill log.txt . 当我运行这个Python脚本时,它只显示在屏幕上运行nn.sh的结果,并且它不会将它们保存在填充log.txt However, if I type 但是,如果我输入

/bin/sh nn.sh 172.20.125.44 10 >> log.txt

in the command line, it is correctly saving all the data into the file log.txt . 在命令行中,它正确地将所有数据保存到文件log.txt Any ideas on what goes wrong? 什么出错的想法?

You can't use >> in subprocess calls, instead use stdout parameter: 你不能在子进程调用中使用>> ,而是使用stdout参数:

with open("log.txt", "at") as log:
    call(['/bin/sh', 'nn.sh', '172.20.125.44', '10'], stdout = log)

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

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