-3

I have a problem running the python program. When I run, it prints an error in the terminal :

main filename = sys.argv[1] IndexError: list index out of range

Would you please help me?

CODE:

def main():
filename = sys.argv[1]
rfile = open(filename, mode='r')
wfile = open(filename.split('.')[0]+'.hack',mode='w')
symbolTab = SymbolTable()
parser = Parser(rfile)
code = Code()
i = 0

while parser.hasMoreCommands():
    ctype = parser.commandType()
    if ctype == 'L_COMMAND':
        symbol = parser.symbol()
        symbolTab.addEntry(symbol,i-1)
    else:
        i += 1
    parser.advance()
rfile.close()
user17732522
  • 16,968
  • 2
  • 24
  • 58
Joker
  • 1
  • 4
  • In your own words, where the code says `filename = sys.argv[1]`, what do you think this means? What values do you think should be in `sys.argv`, and why? Where do you expect them to come from, exactly? Did you try to [use a search engine](https://duckduckgo.com/?q=python+sys+argv) in order to understand these things? – Karl Knechtel Mar 29 '22 at 10:25
  • @MisterMiyagi why exactly are we assuming that OP wants the program to open its own source file? – Karl Knechtel Mar 29 '22 at 10:27

1 Answers1

0

Please change filename = sys.argv[1] to filename = sys.argv[0]
For example, when you execute your python file like python3 test.py test, sys.argv[1] will be "test"

filename = os.path.basename(os.path.abspath(__file__)) just as effective

CN-LanBao
  • 371
  • 7