如何解决如何从 python 运行多个外部命令?
我知道有可用的选项,例如 os 和 subprocess,但它们不只是做我想做的事
假设我有一个外部命令列表。myList = ['cd desktop','mkdir spotify']
并且我想从 python 一次运行它们,我不想使用 os.chdir 或任何子进程方法,因为该列表基于用户输入,我不能只知道他们必须将列表的哪个索引放入项目中,请帮助
解决方法
所以,基本的担心是关于 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)
这里有一些额外的链接来理解这些概念:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。