Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

networking - python copy file in local network (linux -> linux) and output

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'

But the problem is the same. (And file_pc is a variable)

Thanks

Edit: Ok, I found this:

command = 'scp', file_pc, file_pi  
p = subprocess.Popen(command, stdout=subprocess.PIPE) 

But no way to have the output... (work with Shell=False)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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 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])

Though It looks like scp doesn't print anything by default if the output is redirected.

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...