我有以下代码,非常适合运行 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/