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>you cant <code>cd</code> out with the <code>subprocess</code> module, the function will run but the path wont change for the python script that is running,<br>
what you can do instead is something like:</p>

<pre><code>import os
if # condition where cd command used:
  os.chdir("path/to/new/dir")
</code></pre>

<p>this will change the path for the python script that you're running and then you can <code>ls</code> to get a different output.</p>

python linux shell command subprocess