Python 3 long filename as argument (python splits it)

947 Views Asked by At

I've been having a problem with taking a command line argument on windows that has a long filename and passing it to a function.

In short the long filename containing spaces is split into separate parts.

I made a fudged together bit of code to give me the command line as a whole, but it's far from ideal as although it works for multiple parameters it doesn't work for LFNs with spaces. (the cludge was made for a different script, I've just copied it across to this one) I've been searching for hours on google trying to figure this out as surely someone else has solved this. I've tried using ArgParse but couldn't get that to give me the filename without splitting it either.

Would someone be good enough to show me some code that demonstrates getting the command line exactly as is (minus the script name) and also getting a full filename.

Thanks, Adam

[edit..] I tried putting quotes around it and it failed still. I know from testing the code that it splits the input on the spaces and removes the quotes. example from a different test:

test.py code:

import sys

print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
for x in range(0, len(sys.argv)):
    print("->" + sys.argv[x])

output:

H:\bin>test "test lfn.txt" 
Number of arguments: 3 arguments. 
Argument List: ['H:\\bin\\test.py', ' test', 'lfn.txt']
->H:\bin\test.py
-> test
->lfn.txt

#

[edit 2] I think it's a Python on Windows bug as double quoting works, sort of:

H:\bin>test ""test lfn.txt""
Number of arguments: 2 arguments.
Argument List: ['H:\\bin\\test.py', ' "test lfn.txt"']
->H:\bin\test.py
-> "test lfn.txt"

original code posted below.

###############################################################################
# Renames a single file to ISO date format: YYYYMMDD-HHMMSS                   #
###############################################################################

import datetime, os, sys

def error_filename():
    print("filename doesn't exist maybe.")
    sys.exit(1)

def error_args():
    print("Renames a single file to ISO date format: YYYYMMDD-HHMMSS")
    print("Requires 1 parameter, the filename to rename")
    sys.exit(2)

def error_rename():
    print("Unable to rename")
    sys.exit(3)

cmds = ""
for x in range(1, len(sys.argv)):
     cmds = cmds + sys.argv[x]
cmds = cmds.strip()
if cmds != "":
    d = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    if os.path.isfile(cmds):
        fn = cmds.split(os.extsep)
        fn[0]=d
        newname = d + "." + fn[1] 
        print(cmds + " -> " + newname)
        try:
            os.rename(cmds, newname)
        except:
            error_rename()
    else:
        error_filename()

else:
    error_args()
1

There are 1 best solutions below

1
On

The error I was having was because Windows 7 was previously defaulting to opening python files in an editor, I changed it manually in the registry to open with python. By doing a clean install on a different machine and letting the python installer set up the path etc it worked fine. The problem lies with a windows registry setting.