python - 如何从 python 运行多个外部命令?
问题描述
我知道有可用的选项,如 os 和 subprocess ,但它们不只是做我想做的事情假设我有一个外部命令列表。myList = ['cd desktop','mkdir spotify']
我想从 python 一次运行它们,我不想使用 os.chdir 或任何子进程方法,因为该列表基于用户输入,我不能只知道它们在列表的哪个索引中必须 cd 进入一个项目,请帮助
解决方案
所以,基本的担心是关于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)
这里有一些额外的链接来理解这些概念:
推荐阅读
- ios - libGDX iOS主页按钮杀死游戏
- vue.js - vue-form-generator github repo 声明它支持“自定义样式”。文档在哪里?
- php - 如何将消息从另一台服务器“传递”到 php 脚本?
- r - 从 cut() 的间隔中提取值
- java - 从 MySQL 数据库中存储和检索盐
- php - Htaccess 重写以删除不适用于目录的 .php 扩展名
- java - JsonMappingException:无限递归
- linked-list - 在链表中包含头节点和尾节点有什么好处?
- debugging - 如何在 CLion 中将所有行设置为断点?
- python - Python super() can't call parent's inherited method