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

时间:2018-07-18 15:12:21

标签: python python-2.7 command subprocess

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

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

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

1 个答案:

答案 0 :(得分:0)

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

subprocess.call('your_first_command.sh; your_real_work.sh', shell=True)
相关问题