简体   繁体   中英

Open Shell within Python Subprocess

I have a script that opens a new shell with different conditions than the standard shell, let's call it ./new_shell <arg> . I need to run ./new_shell <arg> in a Python script, then run commands within that shell, then exit the shell and continue executing my script as usual. How can I do this?

The goal, in pseudo code, for reference:

for arg in args:
    subprocess.run(['./new_shell ' + arg], shell=True) #this doesn't behave as I want, because I need the shell to be automated, not manual
    subprocess.run([<various scripts that need to be run within new_shell])
    subprocess.run([<exit_shell>]) #don't know how to do this

Thank you very much!

My solution was to use Popen as follows:

for arg in args:
    pro = subprocess.Popen(['new_shell', arg],
                           stdin=subprocess.PIPE,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
    inpt = <script_to_be_run_in_shell> + <arguments> +'\n'
    out, err = pro.communicate(inpt.encode())

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