【问题标题】:subprocess ls examples/* no fuch file or directory [duplicate]子进程ls示例/ *没有这样的文件或目录[重复]
【发布时间】:2016-05-04 11:15:04
【问题描述】:
>>> import subprocess
>>> child = subprocess.Popen(["ls", "examples/*"], stdout=subprocess.PIPE)
>>> ls: examples/*: No such file or directory

但是从终端它可以工作

Beagle:kumarshubham$ ls examples/*
examples/convert_greyscale.py       examples/feat_det_harris_corner.py  examples/read_display_image.py
examples/example_set_roi.py     examples/manipulate_img_matplotlib.py   examples/remove_matplotlib_cache.py

谁能指导我哪里出错了?

【问题讨论】:

    标签: python python-2.7 subprocess


    【解决方案1】:
    import subprocess
    child = subprocess.Popen(["cd /to-your-PATH/; ls", "examples/*"],shell=True, stdout=subprocess.PIPE)
    child.stdout.read()
    

    【讨论】:

      【解决方案2】:

      这是因为 (*) 使用了通配符。您需要提供 shell=True 以通过 shell 解释器执行命令

      >>> import subprocess
      >>> child = subprocess.Popen(["ls", "examples/*"], stdout=subprocess.PIPE, shell=True)
      

      【讨论】:

        【解决方案3】:

        你应该在你的Popen调用中添加shell=True,即使*在你的情况下是无用的,ls examples/应该返回相同的输出:

        child = subprocess.Popen(["ls", "examples/*"], stdout=subprocess.PIPE, shell=True)
        

        另外,更 Pythonic 的方法可能是:

        import os
        os.listdir('examples')
        

        【讨论】:

          【解决方案4】:

          你可以使用额外的参数shell=True,那么它会是这样的:

          child = subprocess.Popen(["ls", "examples/*"], shell=True,  stdout=subprocess.PIPE)
          

          注意!即使这样也行, - 根据官方 python 文档https://docs.python.org/2/library/subprocess.html 使用 shell=True 可能是一个安全问题。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-02-10
            • 2021-06-11
            • 1970-01-01
            • 1970-01-01
            • 2013-03-31
            • 2019-09-06
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多