[使用subprocess.run()在python中执行shell命令

问题描述 投票:0回答:1

我具有运行命令的功能,可将所有文件从子文件夹移动到一个文件夹。

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文件夹并在不存在的情况下创建它,但它似乎没有运行。

我怀疑这可能是路径问题。造成这种情况的可能原因是什么,并且有修复程序吗?

python ubuntu subprocess
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.