使用python与bash

时间:2016-05-22 15:37:33

标签: python bash popen

import os
ot = os.popen("%s") %"ls"
TypeError: unsupported operand type(s) for %: 'file' and 'str'

我无法弄清楚为什么会发生错误。我的意思是纯粹的字符串操作,对吧?任何帮助都可以得到赞赏。

1 个答案:

答案 0 :(得分:6)

由于交互式shell,Python非常棒。

尝试:

>>> import os
>>> os.popen("%s")
<open file '%s', mode 'r' at 0x10d020390>

你可以在你面前看到错误。 os.popen的结果是一个文件。然后,您正在应用字符串操作。

将您所拥有的内容翻译为您正在尝试的内容,尝试:

>>> os.popen("%s" % "ls").read()

或者,直接:

>>> os.popen("ls").read()

subprocess module通常是首选:

>>> import subprocess
>>> subprocess.check_output("ls")