Warning
This book is new. If you'd like to go through it, then join the Learn Code Forum to get help while you attempt it. I'm also looking for feedback on the difficulty of the projects. If you don't like public forums, then email help@learncodethehardway.org to talk privately.
Exercise 28: sh
You are now going to continue your TDD style process, but you'll add a small hack session to start. The best method for working in TDD is to actually not write the tests first but instead to work this way:
- Spend 45 minutes doing a hack to study the problem. This is called a "spike" and is intended to iron out issues you may run into or research things you need to know.
- Plan out what you'll probably need to implement with a TODO list.
- Turn this plan into a TDD test.
- Run the test to make sure it fails.
- Write the code for the test, using what you learned from the spike.
- Audit your code and test to confirm quality.
This process is what I see TDD fanatics actually use when pressed with a problem they haven't studied before. It is also much more practical to work out a fast hack to get your mind going and to study the problem and then get serious about the work. If anyone tells you this isn't TDD, just don't tell them you did a spike first. They'll never know.
Exercise Challenge
In this exercise you'll implement the shell part of the Unix sh tool. You use sh all day when you code, as it's what runs inside Terminal (PowerShell is different) and runs your other programs. Typically this will be bash, but it might be fish, csh, or zsh.
The sh tool is a massive program to implement as it also supports a full programming language to automate your system. We are not going to implement the programming language, just the command line process running part.
To complete this task you'll need the following libraries:
- subprocess to launch other programs.
- readline to get input from the user and support history.
You aren't making a full Unix sh with piping and everything, but you could implement nearly everything except the programming language. Your implementation should be able to do the following:
- Start with a prompt using readline and take a command to run from the user.
- Parse the command into executable and arguments.
- Use subprocess to launch the command with the arguments and control all the output.
To get started you can do your spike to study either readline or subprocess or both, whichever you think is necessary or unfamiliar. Once you do your spike then you start writing the tests and implementing the sytem.
Study Drills
- Can you implement pipes? That's when you type history | grep python and the | sends the output of history to the input of grep.
Further Study
You can study my project python-lust if you want to learn even more about Unix process and resource management. It's not very large and full of many little tricks.