How do I find out the basename of the file in this case?
>>> from os.path import basename
>>> basename('C:\\test.exe --help')
'test.exe --help'
Result should be just test.exe
without --help
or any other arguments.
How do I find out the basename of the file in this case?
>>> from os.path import basename
>>> basename('C:\\test.exe --help')
'test.exe --help'
Result should be just test.exe
without --help
or any other arguments.
There is shlex
module that mimics behaviour of a Unix shell (but since command.com used to mimic some of its features, it should work too). It'll also will tolerate a quotes (but note that I used raw strings in example):
>>> import shlex
>>> print shlex.split(r'C:\\test.exe --help')
['C:\\test.exe', '--help']
>>> print shlex.split(r'"C:\\test.exe" --help')
['C:\\test.exe', '--help']
>>> print shlex.split(r'"C:\\Program Files\\test.exe" --help')
['C:\\Program Files\\test.exe', '--help']
So take first string returned from shlex.split
, and pass to basename.
If you want to get rid of treating backslashes \
as escape sequences, you should construct shlex
object explicitly:
>>> from shlex import shlex
>>> lex = shlex('C:\\test.exe --help')
>>> lex.whitespace_split = True
>>> lex.escape = ''
>>> list(lex)
['C:\\test.exe', '--help']
Well the problem is that, at least on Linux, 'test.exe --exe' is a valid filename. So that is the reason why python does not try to clean filenames from 'parameters'. I looked at windows docs and it looks like you also make file named 'test.exe --exe'. So, it really depends on what you are trying to achieve.
Also have a look at this: What is the most correct regular expression for a UNIX file path?
You should then probably check if file exists, if it does not then use regular expression or the shlex module to strip the parameters...
import os, shlex
print(os.path.basename(shlex.split(r'"C:\\test.exe" --help')[0]))