是否可以使用argparse获取脚本的路径? [英] Is it possible to obtain the path of the script using argparse?
问题描述
如果可能的话,我想知道如何获取用argparse存储脚本的路径,因为如果我从另一个路径运行脚本(我的脚本路径在%PATH%变量中),它将使用默认情况下,相对路径。
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]
但我想知道是否有可能直接从argparse模块。
but I would like to know if it is possible to acess it directly from the argparse module.
感谢
编辑:我收到了答复,很满意。
为了更好地解释这个问题:我有一个名为mdv.py的脚本,用于将markdown文件转换为html。我想从计算机的任何位置调用它。
脚本位于:
c:\Python27\markdown
Thanks 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
在此路径中,我还有其他文件和文件夹模板生成我的HTML(用于页眉,正文和页脚的默认样式表和文件)。
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).
这些文件位于:
C:\Python\27\markdown\markdown\templates
These files are in: C:\Python\27\markdown\markdown\templates
当我从非标准路径(例如c:\dropbox\public)调用脚本时,它将在c:\dropbox\public\这些模板的模板中查找,而不是在c:\中\python27\markdown\保存它们的模板。
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.
推荐答案
我认为您正在寻找< a href = http://docs.python.org/dev/library/argparse.html#prog rel = nofollow noreferrer> prog
参数 ;您可以使用%(prog)s
将 sys.argv [0]
插入到您的帮助字符串中。
I think you are looking for the prog
parameter; you can interpolate sys.argv[0]
into your help strings with %(prog)s
.
在创建 ArgumentParser()
时可以设置 prog
的值实例它是第一个参数:
The value for prog
can be set when creating the ArgumentParser()
instance; it is the first parameter:
parser = argparse.ArgumentParser('some_other_name')
,并且可以使用 .prog
属性进行检索:
and can be retrieved with the .prog
attribute:
print(parser.prog) # prints "some_other_name"
但是, argparse
调用 os.path.basename()
并使用不将程序的目录存储在任何位置。
However, argparse
calls os.path.basename()
on this name, and does not store the directory of the program anywhere.
这篇关于是否可以使用argparse获取脚本的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!