简体   繁体   English

如何使用python代码中的变量命令运行linux cp -r

[英]How can I run linux cp -r with variables command from python code

I would like to run cp -r $src $dest from python code. 我想从python代码运行cp -r $ src $ dest。 The issue raises when I try to pass src and dest as variables and not as strings. 当我尝试将src和dest作为变量而不是字符串传递时,就会出现问题。

What is the easiest way to copy a directory and all subfolders with the files to a new directory? 将目录和带有文件的所有子文件夹复制到新目录的最简单方法是什么?

I've tried: 我试过了:

src='src/dir'
dest='dest/dir/
import os
myCmd = 'cp -R '+src+' '+dest
os.system(myCmd)

I also tried to use subprocess: 我也尝试使用子流程:

subprocess.run(myCmd, shell=True)

or: 要么:

subprocess.run('cp -r "$s" "$d"', shell=True, env={'s': src, 'd':dest} )

It worked only when I specify the src and dest as strings: 仅当我将src和dest指定为字符串时,它才起作用:

subprocess.run('cp -r src/dir dest/dir', shell=True )

Instead of doing a system-level call, use shutil.copytree() : 而不是进行系统级调用,请使用shutil.copytree()

import shutil
source_folder = '/somewhere/some_folder'
dest_folder = '/elsewhere/some_folder'
shutil.copytree(source_folder, dest_folder)

This will work on every platform 这将适用于所有平台

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM