You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python面向对象开发中,如何获取用户输入并传入类方法参数?

解决Python OOP中高效获取用户输入的问题

先修正你代码中的几个问题:

  • uploadtoRemote方法无需重复传入myhost、myusername、mypassword,可以直接使用实例初始化时的属性
  • downloadtoLocal方法中for循环缺少缩进,且sftp.get的路径需要拼接文件名,否则会覆盖本地文件
  • 调用uploadtoRemote时参数数量不匹配(原定义需要5个参数,你只传了4个)

优化后的基础类代码:

import paramiko
import os

class MySFTP:
    def __init__(self, hostname, user, password):
        self.hostname = hostname
        self.user = user
        self.password = password

    def connect_paramiko(self):
        ssh = paramiko.SSHClient()
        ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(self.hostname, port=22, username=self.user, password=self.password)
        print("connected successfully")
        return ssh

    def upload_to_remote(self, remote_path, upload_local_path):
        ssh = self.connect_paramiko()
        sftp = ssh.open_sftp()
        files = os.listdir(upload_local_path)
        for file in files:
            local_file_path = os.path.join(upload_local_path, file)
            remote_file_path = os.path.join(remote_path, file)
            sftp.put(local_file_path, remote_file_path)
        sftp.close()
        ssh.close()

    def download_to_local(self, remote_path, download_local_path):
        '''从远程主机下载文件到本地'''
        ssh = self.connect_paramiko()
        sftp = ssh.open_sftp()
        inbound_files = sftp.listdir(remote_path)
        for file in inbound_files:
            remote_file_path = os.path.join(remote_path, file)
            local_file_path = os.path.join(download_local_path, file)
            sftp.get(remote_file_path, local_file_path)
        sftp.close()
        ssh.close()

针对remote_path、upload_local_path、download_local_path三个参数,以下是三种高效获取用户输入的方法:

1. 基础交互式输入:input()函数

适合快速测试和简单场景,直接在运行时提示用户输入:

if __name__ == "__main__":
    # 获取连接参数
    hostname = input("请输入远程主机地址: ")
    user = input("请输入用户名: ")
    password = input("请输入密码: ")
    
    sftp_client = MySFTP(hostname, user, password)
    
    # 获取文件路径参数
    upload_local = input("请输入本地上传目录路径: ")
    remote_upload_path = input("请输入远程上传目标路径: ")
    sftp_client.upload_to_remote(remote_upload_path, upload_local)
    
    remote_download_path = input("请输入远程下载目录路径: ")
    download_local = input("请输入本地保存目录路径: ")
    sftp_client.download_to_local(remote_download_path, download_local)

2. 命令行参数:argparse模块

适合将脚本作为工具运行,用户通过命令行传入参数,更高效且自动化:

import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="SFTP文件上传下载工具")
    # 连接参数
    parser.add_argument("--hostname", required=True, help="远程主机地址")
    parser.add_argument("--user", required=True, help="用户名")
    parser.add_argument("--password", required=True, help="密码")
    # 文件路径参数
    parser.add_argument("--upload-local", help="本地上传目录路径")
    parser.add_argument("--remote-upload-path", help="远程上传目标路径")
    parser.add_argument("--remote-download-path", help="远程下载目录路径")
    parser.add_argument("--download-local", help="本地保存目录路径")
    
    args = parser.parse_args()
    
    sftp_client = MySFTP(args.hostname, args.user, args.password)
    
    # 执行上传(如果传入了对应参数)
    if args.upload_local and args.remote_upload_path:
        sftp_client.upload_to_remote(args.remote_upload_path, args.upload_local)
    
    # 执行下载(如果传入了对应参数)
    if args.remote_download_path and args.download_local:
        sftp_client.download_to_local(args.remote_download_path, args.download_local)

运行示例:

python your_script.py --hostname abc.com --user user --password user --upload-local /abc/book/lib --remote-upload-path /remote/path --remote-download-path /remote/files --download-local /abc/book/efg

3. 配置文件:configparser模块

适合需要重复使用固定配置的场景,将参数写入配置文件,避免每次输入:
首先创建sftp_config.ini配置文件:

[SFTP]
hostname = abc.com
user = user
password = user
upload_local_path = /abc/book/lib
remote_upload_path = /remote/upload
remote_download_path = /remote/download
download_local_path = /abc/book/efg

然后读取配置的代码:

import configparser

if __name__ == "__main__":
    config = configparser.ConfigParser()
    config.read("sftp_config.ini")
    
    sftp_client = MySFTP(
        config["SFTP"]["hostname"],
        config["SFTP"]["user"],
        config["SFTP"]["password"]
    )
    
    # 执行上传
    sftp_client.upload_to_remote(
        config["SFTP"]["remote_upload_path"],
        config["SFTP"]["upload_local_path"]
    )
    
    # 执行下载
    sftp_client.download_to_local(
        config["SFTP"]["remote_download_path"],
        config["SFTP"]["download_local_path"]
    )

内容的提问来源于stack exchange,提问作者stack overflow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 06:35:24