1

I am building a terminal simulator in Python, and i have the commands stored in arguments, like:

def ls(a):
    for item in os.listdir():
        print item

a = input('Command: ')
a = a.split()

The terminal works like this:

  1. Ask user for input
  2. Splits the input
  3. Uses the first part of input to search a function in locals
  4. If there is one, uses the rest part of input as argument
  5. Calls the function

And i have a problem with cd command.

def cd(a):
    if a == None:
        print('cd')
        print('Change directories')
    else:
        os.chdir(os.getcwd() + '/' + a())

It works when you make it enter a folder without spaces, like when you type cd Windows in the prompt, it works. But the problems start when you try to enter a folder that has spaces in it. When i type, for example, cd Documents Copy, it either enters the folder Documents if there is one, or crashes.

How i can fix it? I had a thought about turning all called function arguments into one, but i dont know how to do that, and there might be other ways.

HackerGamerLV
  • 37
  • 1
  • 9

1 Answers1

1

You need a more sophisticated split() function -- see Split a string by spaces — preserving quoted substrings answer for a potential solution.

UPDATE

If you had a subdirectory called "the dog" with a space in it, in your interpreter you could do:

Command: cd "the dog"

The code modifications would be roughly as follows:

import shlex
import os

def ls(a):
    for item in os.listdir():
        print(item)

def cd(a):
    if a == None:
        print('cd')
        print('Change directories')
    else:
        os.chdir(os.getcwd() + '/' + a)

a = input('Command: ')
a = shlex.split(a)

if len(a) > 1:
    locals()[a[0]](a[1][:99])
    print()
else:
    locals()[a[0]](None)
    print()
Community
  • 1
  • 1
cdlane
  • 40,441
  • 5
  • 32
  • 81