如何将 os.system() 输出存储在 python 中的变量或列表中 [英] How to store os.system() output in a variable or a list in python
问题描述
我试图通过使用以下命令在远程服务器上执行 ssh 来获取命令的输出.
I am trying to get the output of a command by doing ssh on a remote server using below command.
os.system('ssh user@host " ksh .profile; cd dir; find . -type f |wc -l"')
这个命令的输出是 14549 0
Output of this command is 14549 0
为什么输出中有一个零?有没有办法将输出存储在变量或列表中?我也尝试将输出分配给一个变量和一个列表,但我在变量中只得到 0.我使用的是 python 2.7.3.
why is there a zero in the output ? is there any way of storing the output in variable or list ? I have tried assigning output to a variable and a list too but i am getting only 0 in the variable. I am using python 2.7.3.
推荐答案
关于这个有很多很好的 SO 链接.尝试 从 Python 运行 shell 命令并捕获输出或 分配os.system 的输出到一个变量,并防止它显示在屏幕上 初学者.总之
There are many good SO links on this one. try Running shell command from Python and capturing the output or Assign output of os.system to a variable and prevent it from being displayed on the screen for starters. In short
import subprocess
direct_output = subprocess.check_output('ls', shell=True) #could be anything here.
应谨慎使用 shell=True 标志:
The shell=True flag should be used with caution:
来自文档:警告
如果与不受信任的输入结合使用,使用 shell=True 调用系统 shell 可能会带来安全隐患.有关详细信息,请参阅常用参数下的警告.
Invoking the system shell with shell=True can be a security hazard if combined with untrusted input. See the warning under Frequently Used Arguments for details.
查看更多信息:http://docs.python.org/2/库/subprocess.html
这篇关于如何将 os.system() 输出存储在 python 中的变量或列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!