如何在python中显示命令的输出

时间:2014-01-06 22:01:43

标签: shell command python-3.3

我想运行命令df -h来显示磁盘信息,但是当我运行我的代码时,终端中没有显示任何内容,我甚至试图做“df -h> out.txt”然后就出来了。 txt但是也没用。

import sys
import os
import subprocess


def main():
    os.system('clear')
    print("Options: \n")
    print("1 - Show disk info")
    print("2 - Quit \n")
    selection = input('> ')
    if selection == 1:
        subprocess.call(['df -h'], shell=True)
    elif selection == 2:
        sys.exit(0)

if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:1)

使用input()读取用户输入会返回一个字符串。但是,您的if/elif语句正在将selection的内容与整数进行比较,因此比较将始终为False。作为解决方法,请使用:

selection = int(input('> '))
if selection == 1:
   ...