如何在Python3脚本中使用Linux别名

问题描述 投票:0回答:1

我正在尝试在 python 脚本中使用 linux 别名来获取所需的信息 为此,我需要在 python3 脚本中运行 linux 别名。

例如,我正在运行“ll”别名,如第一个屏幕截图所示。

enter image description here

    print('{:/^100}'.format(f' pd_env detect '))
    get_pd_env_cmd = subprocess.run('ll', shell=True,
                                    capture_output=True, text=True,
                                    executable='/bin/csh'
                                    )
    print(get_pd_env_cmd.stdout)
    print('-'*100)
    print(get_pd_env_cmd.stderr)
    exit()

但结果我只收到第二个屏幕截图所示的错误。

enter image description here

////////////////////////////////////////// pd_env 检测 ///// ///////////////////////////////////////


ll:未找到命令。

我的linux shell是csh。 我尝试使用交互式 shell 运行它“csh -ic command”。 据我了解,问题是 python 脚本无法识别 linux 别名。

python python-3.x linux alias csh
1个回答
0
投票

测试你的代码,我发现在我的环境中,shell 别名在 python 中不可用,我得到

/usr/bin/alias: line 2: alias: ll: not found

我的想法是在返回的 python 子进程中运行

alias ll

alias ll='ls -l --color=auto'
通过字符串操作轻松过滤

alias_response.split('=')[1].split("'")[0]
并在以下子进程调用中使用该字符串作为命令

就在我的脑海里......希望它有帮助

© www.soinside.com 2019 - 2024. All rights reserved.