加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python-运行bash脚本以在USB设备安装后自动从USB设备复制内容

发布时间:2020-12-17 17:38:30 所属栏目:Python 来源:网络整理
导读:我有一个python脚本可将所有文件从USB存储设备复制到Ubuntu计算机中的目标文件夹.我以前从未用Python编程过. import osimport shutilfrom shutil import copytree,ignore_patternsfiles = os.listdir('/media/user/HP drive')destination = '/home/user/Docu

我有一个python脚本可将所有文件从USB存储设备复制到Ubuntu计算机中的目标文件夹.我以前从未用Python编程过.

import os
import shutil
from shutil import copytree,ignore_patterns

files = os.listdir('/media/user/HP drive')

destination = '/home/user/Documents/Test/%s'
try :
    for f in files:
        source = '/media/user/HP drive/%s' % f
        copytree(source,destination,ignore=ignore_patterns('*.pyc','tmp*'))    
except Exception as e:
    print(e)

上面的脚本运行良好,但是它在Test文件夹内用锁定符号创建了一个文件夹%s.当我删除%s而只使用

destination = '/home/user/Documents/Test/'

它给我[Errorno 17]文件存在.

这是安装USB设备时要运行的bash脚本(copy.sh).

#!/bin/sh

python /var/www/html/copy_flash.py    #This doesn't work.

# echo "My message" > /var/www/html/thisisaverylongfilename.txt #This works

因此,当我插入USB时,python命令不起作用,但是echo命令起作用.

这是我在/etc/udev/rules.d/test.rules中添加的行

ACTION=="add",KERNEL=="sdb*",RUN+="/var/www/html/copy.sh"

是因为bash脚本运行时USB驱动器未准备好吗?

>如何将USB驱动器的内容复制到常规文件夹而不是%s中?
>我实际上如何复制内容?

最佳答案
为了不使用%s,可以使用format方法.

source = '/media/users/HP/{path}'.format(path=your_filename_here)

您可以在括号内使用任何名称,这些名称将创建格式的关键字参数.您也可以使用转换为位置参数的数字.
一个例子:

'Hello {0}! Good {1}'.format('DragonBorn','Evening!')

来自shutil的copytree还要求目标不存在.因此,您将需要检查目标位置是否存在,如果存在则将其删除.您可以为此使用os.rmdir和os.path.exists. Shutil也可能具有同等功能.

https://docs.python.org/3.5/library/shutil.html#shutil.copytree

您可以执行以下检查并使用以下命令复制树:

if os.path.exists(destination):
    if os.listdir(): # If the directory is not empty,do not remove.
        continue
    os.rmdir(destination)
shutil.copytree(source,destination)

如果要删除目录下的整个树,则可以使用shutil.rmtree().

if os.path.exists(destination):
    shutil.rmtree(destination)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读