Python argparse报错:'Namespace'对象不存在'myFile'属性的问题求助
Hey there! Let's break down what's going wrong here and fix that error quickly.
The Root Cause
The issue comes from a misunderstanding of how argparse's metavar parameter works. When you set metavar="myFile" in parser.add_argument("--graph", ...), you're only changing what shows up in the help text (like when you run python script.py --help). The actual attribute name stored in the args Namespace is still graph—not myFile. That's why getattr(args, 'myFile') throws an error.
Solution 1: Use the Correct Attribute Name
The simplest fix is to reference the actual attribute name that argparse created, which matches the --graph flag. Update your code like this:
if __name__ == "__main__": parser = argparse.ArgumentParser(description="write data file for optimization model") parser.add_argument("--graph", metavar="myFile", default=" ", type=str, help="graphml file") parser.add_argument("--budget", type=int, default=0, help='budget') parser.add_argument("--nsamples", type=int, default=0,help='number of random samples') args = parser.parse_args() # Access the attributes using the correct names budget = args.budget graphFile = args.graph # Changed from 'myFile' to 'graph' nsamples = args.nsamples roadSegGraph = nx.read_graphml(graphFile)
Solution 2: Force the Attribute Name with dest
If you really want the attribute to be named myFile (instead of graph), you can use the dest parameter in add_argument to explicitly set the attribute name. Here's how:
parser.add_argument("--graph", dest="myFile", metavar="myFile", default=" ", type=str, help="graphml file")
With this change, getattr(args, 'myFile') will work as expected, since argparse now maps the --graph flag to the myFile attribute in the Namespace.
A Quick Note on Your Default Value
Also, using default=" " (a single space) for your graph file might cause issues with nx.read_graphml later—since that's not a valid file path. Consider setting a meaningful default (like a common filename) or adding required=True to force users to provide the file path when running the script.
内容的提问来源于stack exchange,提问作者Prynz58




