python - 在ubuntu中使用Python显示目录内容

标签 python os.system

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

 import os

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

我希望它从“桌面”目录中“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的内容。

<小时/>

Fabric

如果您的应用程序需要大量使用 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)

关于python - 在ubuntu中使用Python显示目录内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33612244/

相关文章:

python - 编译 python 时 --enable-optimizations 做了什么?

python - 在 Pandas 中过滤数据框时复制警告

python - 如何从 os.system() 获取输出?

Python 操作系统故障

python - 使用Python3显示年龄(以秒为单位)

python - 为什么我的 Cython cimport 无法导入 pxd 文件?

python - 如何使用 lxml 有效地解析这个包含嵌套元素的巨大 XML 文件?

python - 子进程相对于 os.system 的优势

python - 如何使用Python在多个CPU核心上运行外部程序?

python - 需要通过os.system()在mysql查询中使用python变量