Skip to main content
 首页 » 编程设计

python之如何在 python 中使用 os.system() 来运行 shell 命令

2024年11月01日12dudu

在某些 shell 脚本中,您需要确认“yes”才能运行 shell,嗯,更简单的方法是使用“yes”和管道,如下所示:

yes | test.py 

然后,您可以自动运行 shell 脚本而无需再回答"is"。 今天,当我通过尝试在 python 中使用它时:os.system("yes|**.sh"),我遇到了一个错误。

这是我的 test.py 文件:

import os 
def f(): 
    cmd1 = "yes | read "           
    os.system(cmd1) 
f() 

然后在 shell 中输入:python test.py 运行。故障信息是: 是:标准输出:破管 是:写入错误

但是如果我在 shell 中输入“yes|read”,它运行良好。 谁能告诉我为什么?

请您参考如下方法:

试试这个

import os 
def f(): 
    cmd1 = "echo 'yes' | read " 
    os.system(cmd1) 
f()