Python3 运行别名 Bash 命令

标签 python bash shell

我有以下代码,非常适合运行 ls 命令。我有一个 bash 别名,我使用 alias ll='ls -alFGh' 是否可以让 python 运行 bash 命令,而无需 python 加载我的 bash_alias 文件、解析,然后实际运行完整命令?

import subprocess

command = "ls"  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)

#Launch the shell command:
output = process.communicate()

print (output[0])

尝试使用 command = "ll"我得到的输出是:

/bin/sh: ll: command not found
b''

最佳答案

你不能。当您运行 python 进程时,它不知道 shell 别名。有一些简单的方法可以将文本从父进程传递到子进程(IPC 除外)、命令行以及通过环境(即导出的)变量。 Bash 不支持导出别名。

来自 man bash 页面:对于几乎所有用途,别名都被 shell 函数取代。

Bash 确实支持导出函数,所以我建议您将别名设置为一个简单的函数。这样它就从 shell 导出到 python 到 shell。例如:

在 shell 中:

ll() { ls -l; }
export -f ll

在Python中:

import subprocess

command = "ll"  # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)

output = process.communicate()

print(output[0].decode())    # Required if using Python 3

由于您使用的是 print() 函数,我假设您使用的是 python 3。在这种情况下,您需要 .decode(),因为这是一个 bytes 对象已返回。

通过一些技巧,也可以从 python 创建和导出 shell 函数。

关于Python3 运行别名 Bash 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35901022/

相关文章:

python - 在 django 中保存新对象时 UNIQUE 约束失败错误

c - 为什么 execvp() 使用 fork() 执行两次?

java - 从命令行运行JAR文件并指定类路径

linux - Linux 终端中的 For 循环

用于计算多个文件平均值的 Linux Bash 脚本

python - 在 Qt Designer 中使用 PySide 自定义小部件

Python3 - 索引超出范围(维吉尼亚密码)

python - PyQt5 抓取并保存屏幕部分

bash - 通过 bash 别名修改 $PATH 变量

bash - 每次音量为零时,如何使用 ffmpeg 分割 mp4 视频?