简体   繁体   中英

Running a command as the first command in subprocess

I have a function that will open a terminal:

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

I want to run a command in this newly opened terminal before anything is done in it. For example:

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

Does subprocess allow a way for me to run a "first command" during the initialization of the shell?

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

subprocess.call('your_first_command.sh; your_real_work.sh', shell=True)

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