【问题标题】:How to run Python script in FTP server using Python?如何使用 Python 在 FTP 服务器中运行 Python 脚本?
【发布时间】:2020-05-23 11:39:08
【问题描述】:

我想使用另一个带有 FTP 的 Python 脚本来运行位于服务器上的 Python 脚本。

下面是我要运行的 (hello.py) 文件位置。

from ftplib import FTP

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

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

【问题讨论】:

    标签: python scripting ftp ftplib


    【解决方案1】:

    您可以使用 system() 调用:

    system('python hello.py')
    

    注意:使用 hello.py 脚本的完整路径。

    另一种方法是使用 subprocess 模块。

    【讨论】:

    • 我不认为这是 OP 要求的。
    【解决方案2】:

    无论如何,您都不能在 FTP 服务器上运行任何东西。
    查看类似问题:Run a script via FTP connection from PowerShell
    这是关于 PowerShell,而不是 Python,但没关系。


    您必须拥有其他访问权限。类似于 SSH shell 访问。


    如果您真的想从 FTP 服务器下载脚本并在本地机器上运行,请使用:

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

    如果您不想将脚本存储到本地文件,这也可以:

    r = StringIO()
    ftp.retrbinary('RETR hello.py', r.write)
    exec(r.getvalue())
    

    【讨论】:

      【解决方案3】:

      最好使用 runpy 模块

      import runpy
      
      runpy.run_path("code.py")
      

      更多详情请参考文档页面runpy module documentation

      【讨论】:

      • FileNotFoundError: [Errno 2] 没有这样的文件或目录:'hello.py'
      • hello.py 位于服务器上,而不是本地机器上。
      【解决方案4】:

      这是一个单行代码(不需要模块!):

      exec(open('hello.py','r').read())
      

      【讨论】:

      • 此行将在本地机器的程序目录中搜索文件,“hello.py”位于ftp服务器上。
      • @MahipalSingh 我明白了。
      猜你喜欢
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 2016-06-26
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多