简体   繁体   中英

Executing related os commands in python

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.

Example of what I mean:

  1. User inputs ls
  2. Python prints contents of current directory
  3. Next user inputs cd exampledir
  4. Python executes the command
  5. User inputs ls
  6. Python prints contents of exampledir

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

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

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

Code so far:

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)

you cant cd out with the subprocess module, the function will run but the path wont change for the python script that is running,
what you can do instead is something like:

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

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

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

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

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM