简体   繁体   English

如何从 python 运行多个外部命令?

[英]How do I run multiple external commands from python?

I know there are available options like os and subprocess but they don't just do what I want yet Let's say I have a list of external commands.我知道有可用的选项,如 os 和 subprocess ,但它们不只是做我想做的事情假设我有一个外部命令列表。 myList = ['cd desktop','mkdir spotify'] and I want to run them all at once from python, I don't want to use os.chdir or any sub process method because that list is based up of user input and I can't just know in what index of the list they have to cd into a project, please help myList = ['cd desktop','mkdir spotify']我想从 python 一次运行它们,我不想使用 os.chdir 或任何子进程方法,因为该列表基于用户输入和我不能只知道他们必须在列表的哪个索引中进入项目,请帮助

So, the basic worry comes is about the cd command.所以,基本的担心是关于cd命令。 for which we can make exceptional case by simply spliting and checking if the command is cd which will detect weather the command is cd or not.为此,我们可以通过简单地拆分并检查命令是否为 cd 来确定例外情况,这将检测命令是否为cd的天气。

So we will start of by making a function that will check our command所以我们将首先制作一个 function 来检查我们的命令

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

now we can use our above function to identify if the command is cd or not.现在我们可以使用上面的 function 来识别命令是否是 cd。 Then we need to execute the command for which we will use the function below然后我们需要执行我们将使用下面的 function 的命令

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)

so our final code becomes所以我们的最终代码变成

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)

Here are some extra links to understand the concepts:这里有一些额外的链接来理解这些概念:

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

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