簡體   English   中英

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

[英]execute shell command in python using subprocess.run()

我有一個函數可以運行命令將所有文件從子文件夾移動到一個文件夾。

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文件夾,如果不存在則創建它,但它似乎沒有運行。

我懷疑這可能是路徑的問題。 造成這種情況的可能原因是什么,是否有解決辦法?

您的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM