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

时间:2019-12-11 17:23:30

标签: python ubuntu subprocess

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

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

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

1 个答案:

答案 0 :(得分:0)

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)