Executing related os commands in python
<p>I'm trying to create a simple script in python which is essentially a shell terminal. It will repeatedly ask for input commands and will attempt to execute the given os commands. What I cannot figure out, is how to make Python 'remember' the commands that were executed.</p>

<p>Example of what I mean:</p>

<ol>
<li>User inputs <code>ls</code> </li>
<li>Python prints contents of current directory</li>
<li>Next user inputs <code>cd exampledir</code></li>
<li>Python executes the command</li>
<li>User inputs <code>ls</code></li>
<li>Python prints contents of <code>exampledir</code></li>
</ol>

<p>Since the command sequence is <code>ls</code> > <code>cd exampledir</code> > <code>ls</code> I expect the program to return the contents of the exampledir, but instead the output of the two <code>ls</code> commands is the same.</p>

<p>Is there a way to make Python somehow 'remember' the commands that were executed and execute next command based on the previous ones?</p>

<p>I know you can use something like <code>cd exampledir &amp;&amp; ls</code> but this is not what I'm looking for. The commands must be executed separately like in a shell terminal.</p>

<p>Code so far:</p>

<pre><code>import subprocess

while True:
    cmd = input("Command to Execute: ")
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out = p.communicate()[0]
    print(out)
</code></pre>

<p>The thing that you have to understand is: you want to write a <strong>full</strong> interpreter of shell commands. That means: any command that alters the <strong>state</strong> of your <strong>shell</strong> ... needs to well, change some internal state. </p>

<p>Meaning: your python "interpreter" starts within a certain directory. So when you tell the interpreter to <strong>change</strong> the directory, it can't just send that request to some shell that goes away one second later.</p>

<p>In other words: you can't have it both ways. Either you pass down <strong>all</strong> commands into a sub process; leading to the problem that makes up your question. Or your "interpreter" does "all the work" itself. </p>

<p>And just for the record: as you might have guessed - writing a "shell" is a complex task. What makes you think that you should re-invent that wheel?</p>

python linux shell command subprocess