根据以下说明,不幸的是我遇到了问题: 如何自动将 USB(闪存)驱动器的内容复制到另一个目录?
我希望连接到计算机的任何 USB 棒/USB 硬盘都能自动复制到特定目录。由于计算机充当服务器,因此一切都应自动完成。无需连接键盘、鼠标或显示器。
如果您知道一个可以做到这一点的程序,当然可以告诉我。
到目前为止,我已经将脚本修改为我的目录:
#!/usr/bin/env python3
import subprocess
import time
import shutil
#--
target_folder = "/mnt/Sicherungen"
excluded = []
#--
def get_mountedlist():
return [(item.split()[0].replace("├─", "").replace("└─", ""),
item[item.find("/"):]) for item in subprocess.check_output(
["/bin/bash", "-c", "lsblk"]).decode("utf-8").split("\n") if "/" in item]
def identify(disk):
command = "find /dev/disk -ls | grep /"+disk
output = subprocess.check_output(["/bin/bash", "-c", command]).decode("utf-8")
if "usb" in output:
return True
else:
return False
done = []
while True:
mounted = get_mountedlist()
new_paths = [dev for dev in get_mountedlist() if not dev in done and not dev[1] == "/"]
valid = [dev for dev in new_paths if (identify(dev[0]), dev[1].split("/")[-1] in excluded) == (True, False)]
for item in valid:
target = target_folder+"/"+item[1].split("/")[-1]
try:
shutil.rmtree(target)
except FileNotFoundError:
pass
shutil.copytree(item[1], target)
done = mounted
time.sleep(4)
但不幸的是,它随后不起作用并显示以下内容:
Traceback (most recent call last):
File "/home/elias/Documents/copy_flash.py", line 29, in <module>
valid = [dev for dev in new_paths if (identify(dev[0]), dev[1].split("/")[-1] in excluded) == (True, False)]
File "/home/elias/Documents/copy_flash.py", line 29, in <listcomp>
valid = [dev for dev in new_paths if (identify(dev[0]), dev[1].split("/")[-1] in excluded) == (True, False)]
File "/home/elias/Documents/copy_flash.py", line 19, in identify
output = subprocess.check_output(["/bin/bash", "-c", command]).decode("utf-8")
File "/usr/lib/python3.10/subprocess.py", line 420, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
file "/usr/lib/python3.10/subprocess.py", line 524, in run
raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['/bin/bash', '-c', 'find /dev/disk -ls | grep /loop0']' returned non-zero exit status 1.
我是 Linux 新手。我以前从未做过这样的事情。如果能得到帮助,我将不胜感激。
答案1
有两个相关的 Bash 脚本这里这可能会有所帮助,并且更容易修改,也可能更可靠。
但是,你的 Python 脚本失败了,因为lsblk
返回你试图grep
在输出中查找的循环设备find /dev/disk -ls
通常不包含这样的设备,因此不会报告该设备的退出状态0
(成功)即此错误信息:
subprocess.CalledProcessError: Command '['/bin/bash', '-c', 'find /dev/disk -ls | grep /loop0']' returned non-zero exit status 1.
并且您没有对此提供适当的处理,因为您的脚本只期望成功。
解决方案是重写脚本来处理这种情况......或者简单地从输出中排除循环设备lsblk
get_mountedlist()
通过在函数中像这样改变它:
def get_mountedlist():
return [(item.split()[0].replace("├─", "").replace("└─", ""),
item[item.find("/"):]) for item in subprocess.check_output(
["/bin/bash", "-c", "lsblk -e 7"]).decode("utf-8").split("\n") if "/" in item]
这只会lsblk
改变lsblk -e 7