我正在尝试编写一个脚本来从我的桌面PC复制我的RaspberryPi中的文件。 这是我的代码:(一部分)
print "start the copy"
path_pi = '//192.168.2.2:22/home/pi/Stock/'
file_pc = path_file + "/" + file
print "the file to copy is: ", file_pc
shutil.copy2(file_pc, path_pi + file_pi)
其实我有这个错误:(法语)
IOError: [Errno 2] Aucun fichier ou dossier de ce type: '//192.168.2.2:22/home/pi/Stock/exemple.txt'
那么,我该怎么办?在尝试复制之前,我必须连接2台机器吗? 我试过了:
path_pi = r'//192.168.2.2:22/home/pi/Stock'
但问题是一样的。 (而file_pc是一个变量)
由于
编辑: 好的,我发现了这个:
command = 'scp', file_pc, file_pi
p = subprocess.Popen(command, stdout=subprocess.PIPE)
但无法获得输出...(使用Shell = False)
答案 0 :(得分:2)
shutil.copy2()
适用于本地文件。 192.168.2.2:22
表示您要通过ssh复制文件。您可以将远程目录(RaspberryPi)挂载到桌面计算机上的本地目录(sshfs
),以便shutil.copy2()
可以正常工作。
如果您想查看命令的输出,请不要设置stdout=PIPE
(注意:如果您设置stdout=PIPE
,那么您应该从p.stdout
读取,否则该过程可能会永远阻止):
from subprocess import check_call
check_call(['scp', file_pc, file_pi])
scp
将打印到您的父Python脚本打印的任何位置。
将输出作为字符串输出:
from subprocess import check_output
output = check_output(['scp', file_pc, file_pi])
虽然如果输出被重定向,scp
默认情况下不会打印任何内容。
您可以使用pexpect
让scp
认为它在终端中运行:
import pipes
import re
import pexpect # $ pip install pexpect
def progress(locals):
# extract percents
print(int(re.search(br'(\d+)%[^%]*$', locals['child'].after).group(1)))
command = "scp %s %s" % tuple(map(pipes.quote, [file_pc, file_pi]))
status = pexpect.run(command, events={r'\d+%': progress}, withexitstatus=1)[1]
print("Exit status %d" % status)
答案 1 :(得分:1)
您是否启用了SSH?这样的事情可以帮到你:
import os
os.system("scp FILE USER@SERVER:PATH")