简体   繁体   中英

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. The issue raises when I try to pass src and dest as variables and not as strings.

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:

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

Instead of doing a system-level call, use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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