Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a user input a filename?

Tags:

python

io

I've written code for an assembler, but I am still new to python.
In my code I have the user input a file that will be converted into an assembly language. I think I've almost got it working, but I can't figure out where the user enters the file name.
I'm in (what I think is) IDLE, and then when I hit F5 it runs in the shell. I'm getting an error, but I'm pretty sure it's because no file name has been entered.

Where is the user supposed to input these kinds of things? Is this done from the python shell, or from the command line, do I need to turn it into an executable?

Can someone help clarify where the user is inputting all this information?

I'll put in a segment of code, although I don't think it's necessary to answer my questions, but maybe it'll give you a better idea of my issue.

if __name__ == '__main__':
import sys

if len(sys.argv) == 1:
    print 'need filename'
    sys.exit(-1)

table = SymbolTable()
parser = Parser(sys.argv[1])
parser.advance()
line = 0

while parser.hasMoreCommands():
    if parser.commandType() == 'L_COMMAND':
        table.addEntry(parser.symbol(), line)
    else:
        line += 1

    parser.advance()

code = Code()
parser = Parser(sys.argv[1])
parser.advance()

var_stack = 16

while parser.hasMoreCommands():
    cmd_type = parser.commandType()

    if cmd_type == 'A_COMMAND':
        number = 32768

        try:
            addr = int(parser.symbol())
        except:
            if table.contains(parser.symbol()):
                addr = table.getAddress(parser.symbol())
            else:
                table.addEntry(parser.symbol(), var_stack)
                addr = var_stack
                var_stack += 1

        bin_number =  bin(number | addr)[3:]
        assembly = '0' + bin_number
        print assembly
    elif cmd_type == 'C_COMMAND':
        assembly = '111'
        assembly += code.comp(parser.comp())
        assembly += code.dest(parser.dest())
        assembly += code.jump(parser.jump())
        print assembly

    parser.advance()

The part to note is at the beginning lines 4-6 where it's checking the file name. So once I run my program I get 'need filename' printed to the screen and an error message that looks like this:

Traceback (most recent call last):
 File "C:\Python27\Assembler.py", line 98, in <module>
  sys.exit(-1)
SystemExit: -1

So where can I input the filename to avoid this error?

like image 468
Chris Searcy Avatar asked Jan 15 '23 03:01

Chris Searcy


1 Answers

The way you have it, Python expects the filename as an argument:

python file.py your_file.asm

If you want to prompt for a filename, use raw_input() (or input() for Python 3):

filename = raw_input('Enter a filename: ') or 'default_file.asm'
like image 164
Blender Avatar answered Jan 18 '23 20:01

Blender