Reputation: 319
I would like to know how to get the path where the script is stored with argparse, if possible, because if I run the script from another path (I have the path of the script in the %PATH% variable) it uses by default the relative path.
I know that I can obtain it using:
import sys
sys.argv[0]
but I would like to know if it is possible to acess it directly from the argparse module.
Thanks Edit: I have my reply and I am satisfied. To explain better the question: I have a script called mdv.py that I use to transform markdown files into html. I would like to call it from any location in my computer. The script is in: c:\Python27\markdown
in this path there are other files and a folder templates that I use to generate my HTML (a default stylesheet and files for header, body and footer).
These files are in: C:\Python\27\markdown\markdown\templates
When I call the script from a non standard path, for example c:\dropbox\public it looks in c:\dropbox\public\templates for these files and not in c:\python27\markdown\templates where they are saved.
Ihope to have better explained. Sorry I'm not a native english speaker.
Upvotes: 2
Views: 743
Reputation: 1121534
I think you are looking for the prog
parameter; you can interpolate sys.argv[0]
into your help strings with %(prog)s
.
The value for prog
can be set when creating the ArgumentParser()
instance; it is the first parameter:
parser = argparse.ArgumentParser('some_other_name')
and can be retrieved with the .prog
attribute:
print(parser.prog) # prints "some_other_name"
However, argparse
calls os.path.basename()
on this name, and does not store the directory of the program anywhere.
Upvotes: 4