【问题标题】:Use Python in ubuntu to show contents of a directory在 ubuntu 中使用 Python 显示目录的内容
【发布时间】:2016-02-10 06:47:32
【问题描述】:

我在主目录中有一个 .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("ls Desktop/")
  • os.chdiros.listdir 相比,您是否有理由需要使用外部进程?
  • 另外,旁注:如果您确实需要运行外部进程,os.system 比使用各种 subprocess 函数更慢/更不安全/更不灵活。 os.system 在子 shell 中启动所有命令(这会引入参数解析、shell 元字符等可能存在的可靠性和安全性问题),其中类似subprocess.check_call 的命令和参数的list 既更快又更安全。
  • How do I "cd" in python的可能重复

标签: python os.system


【解决方案1】:

您必须考虑os.system 在子shell 中执行命令。因此1)python启动一个子shell,2)目录改变,3)然后子shell完成,4)返回之前的状态。

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

os.chdir("Desktop")

总是尝试通过os.system (os.listdir) 或subprocess 以外的其他方式进行操作(这是shell 中用于命令控制的优秀模块)

【讨论】:

    【解决方案2】:

    这两个调用是相互独立的。在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 调用时发生这种情况的原因是每个os.system 都会生成一个新的shell 来运行命令。所以新的 shell 会改变目录,然后退出。然后生成一个全新的 shell(在原始目录中,而不是更改后的目录中)并运行。
    • "ls Desktop/" 会更短 ;)
    猜你喜欢
    • 2013-12-02
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 2011-01-29
    • 2019-06-29
    • 1970-01-01
    • 2013-05-20
    • 2018-12-01
    相关资源
    最近更新 更多