Python3 Run Alias Bash Commands

你离开我真会死。 提交于 2021-02-18 18:54:37

问题


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])

Trying with command = "ll" the output I get is:

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

回答1:


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.

From the man bash pages: For almost every purpose, aliases are superseded by shell functions.

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:

In the shell:

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

In 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

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.

With a bit of hackery it is possible to create and export shell functions from python as well.



来源:https://stackoverflow.com/questions/35901022/python3-run-alias-bash-commands

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!