在 ubuntu 中使用 Python 来显示目录的内容

Use Python in ubuntu to show contents of a directory

我的主目录中有一个 .py 文件,其中包含以下三行:

 import os

 os.system("cd Desktop/")
 os.system("ls")

我希望它从 "Desktop" 目录 "ls" 但它显示 /home 目录的内容。
我查看了这些页面:
Calling an external command in Python
http://ubuntuforums.org/showthread.php?t=729192
但我不知道该怎么办。有人可以帮助我吗?

这两个电话是分开的。在 os.system 的连续调用之间没有保留上下文,因为每次调用都会产生一个新的 shell 。首先 os.system("cd Desktop/") 将目录切换到 Desktop 并退出。然后一个新的shell在原来的文件夹里执行ls

尝试用 &&:

链接你的命令
import os

os.system("cd Desktop/ && ls")

这将显示目录 Desktop 的内容。


面料

如果您的应用程序将大量使用 os,您可以考虑使用 python-fabric。它允许您使用更高级别的语言结构(如上下文管理器)来简化命令行调用:

from fabric.operations import local
from fabric.context_managers import lcd

with lcd("Desktop/"): # Prefixes all commands with `cd Desktop && `
    contents=local("ls", capture=True)

你要考虑到os.system执行子shell中的命令。因此 1) python 开始一个 sub-shell,2) 改变目录,3) 然后 sub-shell 完成,4) return 到之前的状态。

要强制更改当前 目录,您应该这样做:

os.chdir("Desktop")

总是 尝试通过其他方式做到这一点,通过 os.system (os.listdir),或者通过 subprocess (这是 shell)

中用于命令控制的优秀模块