从Python在控制台中运行WinSCP命令 [英] From Python run WinSCP commands in console

查看:80
本文介绍了从Python在控制台中运行WinSCP命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用子进程从Python类运行WinSCP的一些命令.

I have to run a few commands of WinSCP from a Python class using subprocess.

目标是连接未安装FTP的本地Windows计算机和Windows服务器并下载一些文件.这就是我尝试过的

The goal is to connect a local Windows machine and a Windows server with no FTP installed and download some files. This is what I tried

python    
proc = subprocess.Popen(['WinSCP.exe', '/console', '/WAIT',  user:password@ip:folder , '/WAIT','get' ,'*.txt'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

通过此操作,我可以打开WinSCP控制台并连接到服务器,但是它不执行 get 命令.是不是因为 get 是在Windows控制台而不是WinSCP控制台上执行的?

With this I get it to open the WinSCP console and connect to the server, but it doesn't execute the get command. Is the problem because the get is executed on the Windows console and not in the WinSCP console?

我还尝试将 winscp.exe/console 替换为 winscp.com/command .

有什么办法吗?

推荐答案

如果要在不生成脚本文件的情况下执行操作,则可以使用如下代码:

If you want do without generating a script file, you can use a code like this:

import subprocess

process = subprocess.Popen(
    ['WinSCP.com', '/ini=nul', '/command',
     'open ftp://user:password@example.com', 'get *.txt', 'exit'],
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in iter(process.stdout.readline, b''):  # replace b'' with '' for Python 2
    print(line.decode().rstrip())

代码使用:

  • /command switch to specify commands on WinSCP command-line;
  • winscp.com instead of winscp.exe, as winscp.com is a console application, so its output can be read by Python.

尽管在命令参数中有空格(例如文件名),但是将数组用作参数是行不通的.然后,您将必须自行格式化完整的命令行.请参见子进程中的Python双引号.执行WinSCP脚本时,Popen不起作用.

Though using the array for the arguments won't work, if there are spaces in command arguments (like file names). Then you will have to format the complete command-line yourself. See Python double quotes in subprocess.Popen aren't working when executing WinSCP scripting.

这篇关于从Python在控制台中运行WinSCP命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆