【问题标题】:execute shell command in python using subprocess.run()使用 subprocess.run() 在 python 中执行 shell 命令
【发布时间】:2019-12-11 17:23:30
【问题描述】:

我有一个函数可以运行命令将所有文件从子文件夹移动到一个文件夹。

def move_images_to_one_folder(scr, dst):
    if not os.path.exists(dst):
        os.makedirs(dst)
        print('Destination Created: ', dst)

    cmd = 'find ' + \
        os.path.join(scr) + ' -type f -print0 | xargs -0 mv -t ' + \
        os.path.join(dst)

    execute_cmd = run([cmd], stdout=subprocess.PIPE)
    print(execute_cmd.stdout.read())

我不断收到文件不存在的错误。

FileNotFoundError: [Errno 2] No such file or directory: 'find /home/yury.stanev/Downloads/lfw-deepfunneled/ -type f -print0 | xargs -0 mv -t /home/yury.stanev/4nn3-project/clean_cnn_outputs/data/': 'find /home/yury.stanev/Downloads/lfw-deepfunneled/ -type f -print0 | xargs -0 mv -t /home/yury.stanev/4nn3-project/clean_cnn_outputs/data/'

我手动创建了目标文件夹并在bash shell 中运行了命令,结果与预期一致,所有文件都已移动。我在函数中添加了一个条件来检查 dst 文件夹,如果不存在则创建它,但它似乎没有运行。

我怀疑这可能是路径的问题。这可能是什么原因,有解决办法吗?

【问题讨论】:

  • 试试run([cmd.split()], stdout=subprocess.PIPE)

标签: python ubuntu subprocess


【解决方案1】:

cmdvariable 输入的是单个字符串。如果要使用subprocess.run() 执行命令,则必须将所有以空格分隔的单独部分放入字符串列表中,如下所示:

execute_cmd = run(["find", os.path.join(scr), "-type", "f", "-print0", "|", "xargs", "-0", "mv", "-t", os.path.join(dst)], stdout=subprocess.PIPE)

【讨论】:

  • 取得了进展,但似乎find 命令要我引用路径find: paths must precede expression: |'. Shouldn't str()` 来解决这个问题?
猜你喜欢
  • 2022-08-18
  • 1970-01-01
  • 2017-05-05
  • 2015-03-08
  • 2020-10-10
  • 2013-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多