将命令作为子进程中的第一个命令运行

问题描述 投票:0回答:1

我有一个打开终端的功能:

def open_next_terminal():
    import subprocess

    def rand(path="/tmp"):
        acc = string.ascii_letters
        retval = []
        for _ in range(7):
            retval.append(random.choice(acc))
        return "{}/{}.sh".format(path, ''.join(retval))

    file_path = rand()
    with open(file_path, "a+") as data:
        data.write(
'''
#!/bin/bash
"$@"
exec $SHELL
'''
        )
    subprocess.call(["sudo", "bash", "{}".format(file_path)])
    return file_path

我想在这个新打开的终端中运行一个命令,然后再进行任何操作。例如:

subprocess.call(["sudo", "bash", "{}".format(file_path)]) #<= is called
ls #<= is run
 #<= some output of files and folders
root@host:~#  #<= the shell is now available

子进程是否允许我在shell初始化期间运行“第一个命令”?

python python-2.7 command subprocess
1个回答
0
投票

只需将shell=True参数传递给subprocess.call,就可以将多个命令(由分号或换行符分隔)作为单个字符串运行。

subprocess.call('your_first_command.sh; your_real_work.sh', shell=True)
© www.soinside.com 2019 - 2024. All rights reserved.