首页 > 解决方案 > 使用 subprocess.run() 在 python 中执行 shell 命令

问题描述

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

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/'

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

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

标签: pythonubuntusubprocess

解决方案


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

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


推荐阅读