2

I am attempting to use the code from here https://stackoverflow.com/a/56454579 to upload files to a server with WinSCP from Python on Windows 10. The code looks like this:

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())

I get the output:

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

Which tells me that the put command isn't properly handling the spaces in the filename. What do I need to change to get this to work? Removing the double quotes around the path gives me a different error (it thinks I'm trying to upload multiple files).

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
joejoejoejoe4
  • 1,206
  • 1
  • 18
  • 38

1 Answers1

3

I do not think you can use an array to provide arguments to WinSCP. The subprocess.Popen escapes double quotes in the arguments using backslash, what conflicts with double double-quotes escaping expected by WinSCP.

You will have to format the WinSCP command-line on your own:

args =  "\"C:\Program Files (x86)\WinSCP\WinSCP.com\" /ini=nul " + \
       f"/command \"open ftp://user:pass@ftp.website.com\" \"put \"\"{path}\"\"\" exit"

(note that I've omitted your option commands, as they are defaults anyway)

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
  • 2
    Thanks, I didn't realize Popen could take arguments like that. Works great. Although I prefer to use raw strings since it makes it a bit more readable: `r'"C:\Program Files (x86)\WinSCP\WinSCP.com" /ini=nul ' + fr'/command "open ftp://user:pass@ftp.website.com" "put ""{path}""" exit'` – joejoejoejoe4 Jan 21 '21 at 07:32