如何用Python从命令行获取文本
我需要在我的Python程序中读取cmd命令提示符窗口里的文本(这个文本每秒都会更新一次)。我用的是Windows 7。有没有人知道怎么做?
补充说明:
我之前没解释清楚。cmd命令提示符已经打开了,我需要读取它打印的所有内容。我得把我的Python程序和命令提示符“连接”起来。
3 个回答
0
只需要使用 subprocess.check_output()
这个命令就可以了。
import subprocess
command = "dir"
output = subprocess.check_output(command, shell=True, text=True)
print(output)
别忘了加上 shell=True
和 text=True
这两个参数。
0
你试过 sys.argv 吗?
import sys
print sys.argv[1:]
第一个参数就是你的文件名。
1
你应该看看这个链接:module-subprocess
>>> subprocess.check_output(["echo", "Hello World!"])
'Hello World!\n'