How to transfer a file between two connected computers in python?
A. Python3
We can use http.server
for this. From SO answer here, SimpleHTTPServer
is moved to http.server
in python3
.
python -m http.server
Python2:
I use SimpleHTTPServer
for this sometimes:
python -m SimpleHTTPServer
...which would serve the files in the current directory on port 8000. Open your web browser on the other computer and download whatever you want.
To know the IP address of your computer, you can use (in Ubuntu) ifconfig
, e.g:
$ ifconfig
enp0s31f6 Link encap:Ethernet HWaddr xx:xx:xx:xx:xx:xx
inet addr:10.0.0.3 Bcast:10.0.0.255 Mask:255.255.255.0
In windows it is ipconfig
.
Then, in the other computer, you send the browser to: http://10.0.0.3:8000.
B. If you have SSH enabled you could use paramiko to connect and SFTP transfer whatever you want.
Some simplistic example code for the sending side:
if os.path.exists(df):
with open(df, 'rb') as f:
packet = f.read(blocksize)
while packet != '':
conn.send(packet)
packet = f.read(blocksize)
Where:
df = 'path/to/data/file'
blocksize = 8192 # or some other size packet you want to transmit.
# Powers of 2 are good.
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Check out paramiko. It can do scp and sftp.
http://www.lag.net/paramiko/