Power Shells vs Compile and Run programs? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Power Shells vs Compile and Run programs? (/thread-41422.html) |
Power Shells vs Compile and Run programs? - RockBlok - Jan-13-2024 Good morning, I decided to take a crack at the edx machine learning course, and I had a question about how to approach writing the code. They seem to run the programs from a powershell using the command line interface whereas everything I've done so far has been compile and run sort of code. The code provided in the class is shown below, and I can call it from a powershell by typing in: python maze.py maze.txt if len(sys.argv) != 2: sys.exit("Usage: python maze - DFS.py maze.txt") m = Maze(sys.argv[1]) print("Maze:") m.print() print("Solving...") m.solve() print("States Explored:", m.num_explored) print("Solution:") m.print() m.output_image("maze.png", show_explored=True)Is the code above a better way to approach these types of problems, or should I aim to import the files and compile them together? I mean, I can compile and run it if I do something like this: #I added this part to make it work sys.argv = ["maze - DFS.py", "maze.txt"] #I added this part to make it work if len(sys.argv) != 2: sys.exit("Usage: python maze - DFS.py maze.txt") m = Maze(sys.argv[1]) print("Maze:") m.print() print("Solving...") m.solve() print("States Explored:", m.num_explored) print("Solution:") m.print() m.output_image("maze.png", show_explored=True) RE: Power Shells vs Compile and Run programs? - Gribouillis - Jan-13-2024 The first solution is more flexible because it lets the user of the program specify the name of the text file contaning the maze, while in the second solution, it can only use the file 'maze.txt' from the current working directory. Python's standard library has a very good module to write command line interfaces: the argparse module. Here it allows you to specify a default text file while allowing the user to choose another text file from argparse import ArgumentParser parser = ArgumentParser(description="Solve a maze and create an image of the solution.") parser.add_argument( "mazefile", nargs="?", default="maze.txt", action="store", metavar="MAZEFILE" ) args = parser.parse_args() print("I will use the file:", args.mazefile)Show help: Use another file: Use the default file:
RE: Power Shells vs Compile and Run programs? - RockBlok - Jan-13-2024 Oh, that's awesome.. Thank you for the helpful explanation and the example of how to set up the code to choose between files. I'll read more on the argparse module for sure. I do see what you are saying now that I've run through a few of these different searches. It's definitely easier to switch files on the command line than having to recompile each time. |