【发布时间】:2016-03-09 19:37:27
【问题描述】:
我有以下代码可以很好地运行 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''
【问题讨论】:
-
我不想让人讨厌,但是你为什么要使用子进程来列出文件呢?
import osos.listdir()不会达到你想要的吗? -
请注意 alias' 是 shell 的东西,而不是 bash 的东西,所以,你的系统不知道别名。您可以通过 shell 执行命令,但这仍然会导致您的别名文件被解析(当 shell 加载时它会解析它)
-
我的实际命令是将命令传送到 docker 容器中,这只是解决问题的一个示例
-
另外,这并不能回答你的问题,但你当然可以改用
subprocess.Popen(['ls', '-alFGh'], stdout=subprocess.PIPE, stderr=None)(尤其是考虑到shell=True通常不受欢迎)。