Somebody came up with the brilliant idea of putting spaces in a filename. I need to do scp from python using that filename, which is problematic because the shell parses the command, and scp has also some quircks regarding spaces. This is my test code:
import subprocess import shlex def split_it(command): return shlex.split(command) #return command.split(" ") def upload_file(localfile, host, mypath): command = split_it('scp {} {}:"{}"'.format(localfile, host, mypath)) print(command) res = subprocess.run(command, stdout=subprocess.PIPE) return res.stdout.decode() upload_file("localfile.txt", "hostname", "/some/directory/a file with spaces.txt") Which gives:
['scp', 'localfile.txt', 'hostname:/some/directory/a file with spaces.txt'] scp: ambiguous target Using the naive version with command.split(" "):
['scp', 'localfile.txt', 'hostname:"/some/directory/a', 'file', 'with', 'spaces.txt"'] spaces.txt": No such file or directory The right, working scp command would be:
['scp', 'localfile.txt', 'hostname:"/some/directory/a file with spaces.txt"'] - Is there a ready solution for this?
- If not, what would be the robust way of doing:
split_it('scp localfile.txt hostname:"/some/directory/a file with spaces.txt"') # returns ['scp', 'localfile.txt', 'hostname:"/some/directory/a file with spaces.txt"']
command = ['scp', localfile, '{}:{}'.format(host, shlex.quote(mypath))]int main(int argc, char** argv)is part of calling convention for any case when you're calling a new executable, no matter what language it's implemented in). Why are you trying to create a string in such a format as to be correctly split into an array, instead of just specifying the array of strings you actually want in the first place?