不能 运行 带有 argparse 的脚本,--datadir 错误

Can't run script with argparse, --datadir error

我正在尝试 运行 一个实现了 argparse 的脚本。当 运行 连接它时,出现以下错误:

usage: compute_distances.py [-h] --datadir DATADIR --info INFO --outdir OUTDIR compute_distances.py: error: argument --datadir is required

我试图添加一个 datadir 参数,但是,我想不出有什么方法不会在之后给我一个语法错误...

//更新2:

删除了所有不立即属于 argparse 实现的代码。

#------------------------------------------------------------------------------
# Main program
#------------------------------------------------------------------------------

# Set up the parsing of command-line arguments
parser = argparse.ArgumentParser(description="Compute distance functions on vectors")
parser.add_argument("--datadir", required=True, 
                    help="Path to input directory containing the vectorized data")
parser.add_argument("--info", required=True, 
                    help="Name of file containing information about documents (name and label)")
parser.add_argument("--outdir", required=True, 
                    help="Path to the output directory, where the output file will be created")
args = parser.parse_args()

# Read the info file with details of the documents to process
try:
    file_name = "%s/%s" % (args.datadir, args.info)
    f_in = open(file_name, 'r')
except IOError:
    print "Input file %s does not exist" % file_name
    sys.exit(1)

# If the output directory does not exist, then create it
if not os.path.exists(args.outdir):
    os.makedirs(args.outdir)

脚本调用

compute_distances.py [-h] "datadir"

如果您 运行 脚本具有:

python compute_distances.py -h

您将在您提供的代码示例中看到 argparse 模块设置的详细使用说明。这基本上打印了每次调用 parser.add_argument(...) 的帮助字符串,例如:

parser.add_argument(
    "--datadir",
    required=True, 
    help="Path to input directory containing the vectorized data"
)

因此您的脚本调用需要看起来更像:

python compute_distances.py \
    --datadir ./my_files/vectorized_data/ \
    --info ./my_files/names_and_labels.txt \
    --outdir ./my_files/output_data/

注意:上面的 \ 只是在每个换行符上继续执行命令(因此对于 Stack Overflow 而言它更具可读性)- 您可以在没有 \ 的情况下将它们全部写在一行中。