3

I want to run Python script located on server using another Python script with FTP.

Below is my (hello.py) file location I want to run.

enter image description here

from ftplib import FTP

ftp = FTP('host')
ftp.login(user='user', passwd = 'password')

print("successfully connected")
print ("File List:")
files = ftp.dir()
print (files)

enter image description here

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Mahipal Singh
  • 144
  • 1
  • 11

4 Answers4

2

You could use a system() call:

system('python hello.py')

Note: use the full path to the hello.py script.

An alternative is to use the subprocess module.

CanciuCostin
  • 1,773
  • 1
  • 10
  • 25
2

You cannot run anything on an FTP server, no matter how.
See a similar question: Run a script via FTP connection from PowerShell
It's about PowerShell, not Python, but it does not matter.


You will have to have another access. Like an SSH shell access.


If you actually want to download the script from the FTP server and run it on the local machine use:

with open('hello.py', 'wb') as f
    ftp.retrbinary('RETR hello.py', f.write)
system('python hello.py')

If you do not want to store the script to a local file, this might work too:

r = StringIO()
ftp.retrbinary('RETR hello.py', r.write)
exec(r.getvalue())
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
0

Better use the runpy module

import runpy

runpy.run_path("code.py")

Refer to the documentation page for more details runpy module documentation

Chems Eddine
  • 153
  • 6
0

Here is a one-liner (no modules required!):

exec(open('hello.py','r').read())
Red
  • 26,798
  • 7
  • 36
  • 58