本地网络(linux-> linux)中的python复制文件并输出 [英] python copy file in local network (linux -> linux) and output
问题描述
我正在尝试编写脚本以从台式机复制RaspberryPi中的文件. 这是我的代码:(一部分)
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)
这篇关于本地网络(linux-> linux)中的python复制文件并输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!