Python3运行Alias Bash命令 [英] Python3 Run Alias Bash Commands
问题描述
我有以下代码非常适合运行ls命令.我有一个使用 alias ll ='ls -alFGh'
的bash别名,是否有可能使python运行bash命令而无需python加载我的bash_alias文件,进行解析,然后实际运行完整命令?
I have the following code that works great to run the ls command. I have a bash alias that I use alias ll='ls -alFGh'
is it possible to get python to run the bash command without python loading my bash_alias file, parsing, and then actually running the full command?
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"我得到的输出是:
Trying with command = "ll" the output I get is:
/bin/sh: ll: command not found
b''
推荐答案
您不能.当您运行python进程时,它不知道shell别名.有几种简单的方法可以将文本从父进程传递到子进程(IPC除外),命令行以及通过环境变量(即导出).Bash不支持导出别名.
You cannot. When you run a python process it has no knowledge of a shell alias. There are simple ways of passing text from parent to child process (other than IPC), the command-line and through environment (i.e. exported) variables. Bash does not support exporting aliases.
在 man bash
页面上:几乎所有目的,别名都被shell函数取代.
Bash 确实支持导出功能,因此建议您将别名改为一个简单的功能.这样就可以将它从shell导出到python再到shell.例如:
Bash does support exporting functions, so I suggest you make your alias a simple function instead. That way it is exported from shell to python to shell. For example:
在外壳中:
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()
函数,所以我假设您正在使用python3.在这种情况下,您需要 .decode()
,因为字节对象返回.
Since you are using the print()
function I have assumed you are using python 3. In which case you need the .decode()
, since a bytes object is returned.
使用一些黑客工具,还可以从python创建和导出shell函数.
With a bit of hackery it is possible to create and export shell functions from python as well.
这篇关于Python3运行Alias Bash命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!