Python subprocess.Popen 中的双引号在执行 WinSCP 脚本时不起作用
Python double quotes in subprocess.Popen aren't working when executing WinSCP scripting
我正在尝试使用此处的代码 通过 WinSCP 从 Windows 10 上的 Python 将文件上传到服务器。代码如下所示:
import subprocess
path = r'C:\mp4s\Sci-Fi Light Flicker.mp4'
process = subprocess.Popen(
['C:\Program Files (x86)\WinSCP\WinSCP.com', '/ini=nul', '/command', 'option batch abort', 'option confirm off', 'open ftp://user:pass@ftp.website.com', f'put "{path}"', 'exit'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in iter(process.stdout.readline, b''):
print(line.decode().rstrip())
我得到输出:
batch abort
confirm off
Connecting to ftp.website.com ...
Connected
Starting the session...
Session started.
Active session: [1] user@ftp.website.com
File or folder '\C:\mp4s\Sci-Fi' does not exist.
System Error. Code: 123.
The filename, directory name, or volume label syntax is incorrect
(A)bort, (R)etry, (S)kip, Ski(p) all: Abort
这告诉我 put
命令没有正确处理文件名中的空格。我需要更改什么才能使其正常工作?删除路径周围的双引号会给我一个不同的错误(它认为我正在尝试上传多个文件)。
我认为您不能使用数组为 WinSCP 提供参数。 WinSCP 期望的subprocess.Popen
escapes double quotes in the arguments using backslash, what conflicts with double double-quotes escaping。
您必须自己格式化 WinSCP 命令行:
args = "\"C:\Program Files (x86)\WinSCP\WinSCP.com\" /ini=nul " + \
f"/command \"open ftp://user:pass@ftp.website.com\" \"put \"\"{path}\"\"\" exit"
(请注意,我省略了您的 option
commands,因为它们是默认值)
我正在尝试使用此处的代码
import subprocess
path = r'C:\mp4s\Sci-Fi Light Flicker.mp4'
process = subprocess.Popen(
['C:\Program Files (x86)\WinSCP\WinSCP.com', '/ini=nul', '/command', 'option batch abort', 'option confirm off', 'open ftp://user:pass@ftp.website.com', f'put "{path}"', 'exit'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in iter(process.stdout.readline, b''):
print(line.decode().rstrip())
我得到输出:
batch abort
confirm off
Connecting to ftp.website.com ...
Connected
Starting the session...
Session started.
Active session: [1] user@ftp.website.com
File or folder '\C:\mp4s\Sci-Fi' does not exist.
System Error. Code: 123.
The filename, directory name, or volume label syntax is incorrect
(A)bort, (R)etry, (S)kip, Ski(p) all: Abort
这告诉我 put
命令没有正确处理文件名中的空格。我需要更改什么才能使其正常工作?删除路径周围的双引号会给我一个不同的错误(它认为我正在尝试上传多个文件)。
我认为您不能使用数组为 WinSCP 提供参数。 WinSCP 期望的subprocess.Popen
escapes double quotes in the arguments using backslash, what conflicts with double double-quotes escaping。
您必须自己格式化 WinSCP 命令行:
args = "\"C:\Program Files (x86)\WinSCP\WinSCP.com\" /ini=nul " + \
f"/command \"open ftp://user:pass@ftp.website.com\" \"put \"\"{path}\"\"\" exit"
(请注意,我省略了您的 option
commands,因为它们是默认值)