简体   繁体   English

在Python子进程中打开Shell

[英]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> . 我有一个脚本,可以用不同于标准外壳的条件打开一个新外壳,我们称它为./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. 我需要在Python脚本中运行./new_shell <arg> ,然后在该Shell中运行命令,然后退出该Shell并继续照常执行我的脚本。 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: 我的解决方案是按如下方式使用Popen

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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