问题描述
我正在尝试编写一个脚本来从我的台式电脑复制树莓派中的文件.这是我的代码:(一部分)
I'm trying to write a script to copy files in my RaspberryPi, from my Desktop PC. Here is my code: (a part)
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)
其实我有这个错误:(法语)
Actually I have this error: (in french)
IOError: [Errno 2] Aucun fichier ou dossier de ce type: '//192.168.2.2:22/home/pi/Stock/exemple.txt'
那么,我该如何继续?我必须在尝试复制之前连接两台机器吗?我试过了:
So, how could I proceed? Must I connect the 2 machines before trying to copy? I have tryed with:
path_pi = r'//192.168.2.2:22/home/pi/Stock'
但问题是一样的.(而file_pc是一个变量)
But the problem is the same. (And file_pc is a variable)
谢谢
好的,我找到了这个:
command = 'scp', file_pc, file_pi
p = subprocess.Popen(command, stdout=subprocess.PIPE)
但没有办法获得输出...(使用 Shell=False)
But no way to have the output... (work with Shell=False)
推荐答案
shutil.copy2()
适用于本地文件.192.168.2.2:22
建议您要通过 ssh 复制文件.您可以将远程目录 (RaspberryPi) 挂载到桌面计算机 (sshfs
) 上的本地目录上,以便 shutil.copy2()
工作.
shutil.copy2()
works with local files. 192.168.2.2:22
suggests that you want to copy files over ssh. You could mount the remote directory (RaspberryPi) onto a local directory on your desktop machine (sshfs
) so that shutil.copy2()
would work.
如果您想查看命令的输出,请不要设置 stdout=PIPE
(注意:如果您设置了 stdout=PIPE
那么您应该从 p.stdout
否则进程可能永远阻塞):
If you want to see the output of a command then don't set stdout=PIPE
(note: if you set stdout=PIPE
then you should read from p.stdout
otherwise the process may block forever):
from subprocess import check_call
check_call(['scp', file_pc, file_pi])
scp
将打印到您的父 Python 脚本打印的任何位置.
scp
will print to whatever places your parent Python script prints.
以字符串形式获取输出:
To get the output as a string:
from subprocess import check_output
output = check_output(['scp', file_pc, file_pi])
虽然看起来 scp
如果输出被重定向,默认情况下不会打印任何内容.
Though It looks like scp
doesn't print anything by default if the output is redirected.
您可以使用 pexpect
让 scp
认为它在终端中运行:
You could use pexpect
to make scp
think that it runs in a terminal:
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)
这篇关于python 在本地网络中复制文件(linux -> linux)并输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!