使用 python 和 bash

Using python with bash

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

我不明白为什么会出现错误。我的意思是它是纯字符串操作,对吧?任何帮助都将不胜感激。

Python 很棒,因为 shell.

尝试:

>>> 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")