12
\$\begingroup\$

I have a big project called 'PyDOS', written in Python 3.4, and it's going very well. Post your answers of anything that could make it look cleaner.

import time
import os
import sys
import random
import operator

def textviewer():
   os.system('cls' if os.name == 'nt' else 'clear')
   print ("Text Viewer.")
   file_name = input("Enter a text file to view: ")
   file = open(file_name, "r")
   print ("Loading text...")
   time.sleep(4)
   os.system('cls' if os.name == 'nt' else 'clear')
   print(file.read())
   input("Press enter to close")
def edit():
    os.system('cls' if os.name == 'nt' else 'clear')
    print ("EDIT")
    print ("-------------")
    print ("Note: Naming this current document the same as a different document will replace the other document with this one.")
    filename = input("Plese enter a file name.")
    file = open(filename, "w")
    print ("FILE: " +filename+".")
    line1 = input()
    line2 = input()
    line3 = input()
    line4 = input()
    line5 = input()
    file.write(line1)
    file.write("\n")
    file.write(line2)
    file.write("\n")
    file.write(line3)
    file.write("\n")
    file.write(line4)
    file.write("\n")
    file.write(line5)
    file.close()
    print ("File successfully saved as: " +filename+"!")
    time.sleep(3)

while True:
   os.system('cls' if os.name == 'nt' else 'clear')
   print ()
   print ("PyDOS VERSION 1.5")
   shell = input("> ")
   if shell == "textviewer":
      print ("Loading Text Viewer...")
      time.sleep(3)
      textviewer()

   elif shell == "edit":
      print ("Loading edit...")
      time.sleep(3)
      edit()

   elif shell == "dir":
      print ("The drive name is A:")
      print ()
      print ("NAME:            TYPE:     MODIFIED:")
      print ("SHUTDOWN.EXE     .EXE      12/01/15 ")
      print ("EDIT.EXE         .EXE      12/01/15 ")
      print ("TEXTVIEWER.EXE   .EXE      12/01/15 ")

   elif shell == "cls":
      os.system('cls' if os.name == 'nt' else 'clear')

   elif shell == 'shutdown':
      print ("Shutting down...")
      time.sleep(3)
      break
   else:
      print(""+ shell+ " is not a reconized command or external file.")
      time.sleep(2)
      os.system('cls' if os.name == 'nt' else 'clear')
\$\endgroup\$
0

3 Answers 3

17
\$\begingroup\$

5 lines ought to be enough for everyone

The following has no meaning. Why 5?

line1 = input()
line2 = input()
line3 = input()
line4 = input()
line5 = input()

Instead let the user end:

def get_lines():
    print("Enter 'END' to end.")
    lines = []
    line = input()
    while line != 'END':
         lines.append(line)
         line = input()
    return lines

Now you can write:

lines = get_lines()
file.write('\n'.join(lines))

Programming with with

with is an extremely useful idiom because it handles closing files automagically.

with open(filename,'r') as f:
    f.read()
# The file is closed automatically :)

If considered harmful (if overused)

So you just started programming and think "Oh the if statements are so good they feel so CS" (I felt that way too when I started programming when I was 15 so I understand you).

BUT so many if and elif are repetitive and you should not repeat yourself.

I would suggest the high level dictionary to accomplish the task more shortly.

command_actions = {
    'textviewer' : textviewer,
    'edit' : edit,
    'dir' : print_dir,
    'cls' : clear_screen,
    'shutdown' : shutdown,
    'help' : give_help
    }
if shell in command_actions:
    action = command_actions[shell]
    action()
else:
    error_message()

Be helpful

It is common and good practice to show some help/info if the user types in help.

Who sleeps too much does not catch fish annoys the user

Why do you sleep up to 4 seconds?

time.sleep(4)

Ok, this emulates an ancient terminal but really, you don't want to make the user wait so much without reason. I suggest time.sleep(0.5)

\$\endgroup\$
2
  • \$\begingroup\$ Thanks for your suggestion! The code has now been updated. All ideas/suggestions will be marked as answer and credited in the edit statement. :) \$\endgroup\$
    – PyxlWuff
    Mar 10, 2015 at 21:04
  • 5
    \$\begingroup\$ @Mrfunny744 you are welcome :) But you should revert back the changes in your question, after you implemented all the improvements you can post another answer. \$\endgroup\$
    – Caridorc
    Mar 10, 2015 at 21:15
10
\$\begingroup\$

Do not repeat yourself

Make yourself a favor and define a function

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')
\$\endgroup\$
2
  • \$\begingroup\$ Thanks for your suggestion! The code has now been updated. All ideas/suggestions will be marked as answer and credited in the edit statement. :) \$\endgroup\$
    – PyxlWuff
    Mar 10, 2015 at 20:51
  • 2
    \$\begingroup\$ No, please don't edit the code in your question, as the page would no longer make sense as a question and answers. Here is how to tell us how you improved your code: meta.codereview.stackexchange.com/questions/1763/… \$\endgroup\$
    – dcorking
    Mar 11, 2015 at 10:40
3
\$\begingroup\$

New ideas: as your "OS" doesn't do that much, your possibilities are pretty limitless (and it can be interesting just "faking it in Python"). You can start emulating what an OS actually does, for example data storage.

If you stick to files/dirs, think out a scheme for representing directories and files as entities/objects/values, connect this with the dir command, then add a type command (display contents of a file).

Perhaps add a notion of "special" files/dirs, that are not actually stored, but their contents are computed by some code (make it easy to register a function as an entry in the filesystem). Bang, you have "device drivers").

Or leave/upgrade the DOS theme and figure out how you would best like to approach storing/accessing data, ie. database that stores data and associated set of tags that are used to store "system" tags (name, content type, create date, permissions, whatever...) as well as arbitrary user tags. Think out a way of how to index your tags for fast search, think about ways how to efficiently search for/uniquely identify file in absence of directories (as always, it's a tradeoff).

Find some persistence scheme for files (and directories, if applicable) - save it all into a yaml file or db, map to real directory on the disk, whatever, as long as it works.

Consider "versioning" - storing multiple versions of the same file - and a method of "addressing" different versions of a file.

Add support for running Python scripts from your simulated files.

Think out how scripts could return some interesting values, and how would you pass them from one script to another, or to the "shell", if there are no (more) redirections.

Oh, and if you won't consider it premature optimization, remove those sleeps from your code, it will start to get slow enough on its own, as you add more functionality.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.