Python NameError: name 'file_name' is not defined

DHW picture DHW · Feb 16, 2016 · Viewed 7.9k times · Source

I'm attempting to write a simple script that will take a filename from the command line and convert that file to a another format. Below is a small simple snippet of code that I am starting with but I keep getting this error: NameError: name 'file_name' is not defined

Here is the code, i'm on a Mac using python 2.7.10.

#!/usr/bin/env python
import sys
import argparse

parser = argparse.ArgumentParser(description='Convert Hex Files')
parser.add_argument('-f', dest=file_name, help='Please Enter the Path to Your File.', type=string)
parser.add_argument('-n', dest=line_length, help='Enter The Desired Line Length.', type=int)
args = parser.parse_args()

print args.file_name
print args.line_length

Answer

Matthew picture Matthew · Feb 16, 2016

In the argparse module, the destinations must be strings.

Therefore, you need to quote the vales that you are assigning to dest.

dest = "file_name"
dest = "line_length"

See the documentation of this option for full details.