2014-03-27 34 views
2

我正在尝试编写脚本来从我的桌面PC中复制RaspberryPi中的文件。 这里是我的代码:(一部分)python在本地网络中复制文件(linux - > linux)并输出

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台机器吗? 我已经tryed有:

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) 

但是没有办法有输出...(与壳牌=假工作)

+0

相关:我如何使用scp或ssh将文件复制到Python中的远程服务器?](HTTP:/ /stackoverflow.com/q/68335/4279) – jfs

回答

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) 
+0

谢谢,它工作正常。 如何获得字符串中的回调? – Guillaume

+0

@Guillaume:我已经更新了答案,以显示如何让子输出 – jfs

+0

好的,但是: OUT = check_output([ 'SCP',file_pc,file_pi]) 打印出来 没什么appers,它停留在第一线。事实上,我想获得一个进度条的百分比 – Guillaume

1

您是否启用SSH?像这样的东西可以帮助你:

import os 
os.system("scp FILE [email protected]:PATH") 
+0

虽然这应该工作,但这不是一个好主意。使用'subprocess.call(['scp',filename,'{} @ {}:{}'.format(user,hostname,path)])'会更清洁一些。 'os.system'产生一个shell,并对文本进行评估,这是不必要的,并且如果您将任何用户输入放入该字段,可能会导致轻松的安全漏洞。 – wolfd