首页 > 解决方案 > 如何从 python 运行多个外部命令?

问题描述

我知道有可用的选项,如 os 和 subprocess ,但它们不只是做我想做的事情假设我有一个外部命令列表。myList = ['cd desktop','mkdir spotify']我想从 python 一次运行它们,我不想使用 os.chdir 或任何子进程方法,因为该列表基于用户输入,我不能只知道它们在列表的哪个索引中必须 cd 进入一个项目,请帮助

标签: pythoncmdterminalcommand

解决方案


所以,基本的担心是关于cd命令的。对于这种情况,我们可以通过简单地拆分并检查命令是否为 cd 来确定例外情况,这将检测命令是否cd存在。

所以我们将从创建一个检查我们的命令的函数开始

import os
import shlex

def is_cd(command: str) -> bool:
    command_split = shlex.split(command)
    return command_split[0] == "cd"  # this returns True if command is cd or False if not

现在我们可以使用上面的函数来识别命令是否是 cd。然后我们需要执行我们将使用下面函数的命令

def run_command(command: str) -> int:
    if is_cd(command):
         split_command = shlex.split(command)
         directory_to_change = ' '.join(split_command[1:])
         os.chdir(directory_to_change)
    else:  # if its a regular command
        os.system(command)

所以我们的最终代码变成

import os
import shlex

def is_cd(command: str) -> bool:
    command_split = shlex.split(command)
    return command_split[0] == "cd"  # this returns True if command is cd or False if not


def run_command(command: str) -> int:
    if is_cd(command):
         split_command = shlex.split(command)
         directory_to_change = ' '.join(split_command[1:])
         os.chdir(directory_to_change)
    else:  # if its a regular command
        return_code = os.system(command)
        if return_code != 0:  # If command failed to run then
            pass  # you can do something here


if __name__ == "__main__":
    user_commands = ["mkdir testdir", "cd testdir"]
    for command in user_commands:
        run_command(command)

这里有一些额外的链接来理解这些概念:


推荐阅读