获取与Python的bash输出 [英] Get bash output with python
问题描述
我试图做一个简单的命令,将让我在Python完全运行bash中,包括输出字符串。
此功能对我在工作中使用的系统工作很大:
导入子DEF运行(命令):
输出= subprocess.check_output(指挥,壳=真)
返回输出
不过,现在我使用它在国内和PATH变量不匹配,一个在我的终端。
所以,当我执行
运行(LS)
我得到这样的:
/ bin / sh的:LS:命令未找到
这是有道理的,因为胡说的PATH我从运行得
印数('的/ usr / bin中/ ENV')
是
PATH = /库/框架/ Python.framework /版本/电流/斌/
现在,我可以通过弥补这一切:
运行('/斌/ LS)
但是,这违背了使用此命令,这是忠实地模仿庆典
壳的全部目的。
我如何运行()使用系统的PATH或创建一个可以工作的同等功能?
(关于使用的危险没有陈词滥调壳=真'
,谢谢。这是无害的命令所有个人使用像 LS
和 PS AXW
)
我要离开这个问题,因为我觉得的run()
上面的命令是有用的,我无法找到SO类似的事情。
不过,我的解决方案是非常系统的具体。但问题是,我崇高的文本2中运行该脚本,并手动替换与
路径:/Library/Frameworks/Python.framework/Versions/Current/bin/
我这样做是因为我不得不让ST2找到蟒蛇
的正确版本的问题。好了,这也将覆盖内ST2全系统的PATH变量,从而阻断我的简单的shell程序,如 LS访问
。
删除了路径:从
固定我的问题<。 / p> ...
行Python.sublime的设置
修改
作为<一个href=\"http://stackoverflow.com/questions/23183924/get-bash-output-with-python/23184244#comment35458820_23184244\">suggested通过mklement0 ,改变线的追加的路径工程,以及:
路径:$ PATH:/Library/Frameworks/Python.framework/Versions/Current/bin/
I'm trying to make a simple command that will let me run bash fully in Python, including output strings.
This function worked great on systems I use at my job:
import subprocess
def run(command):
output = subprocess.check_output(command, shell=True)
return output
However, now I'm using it at home and the PATH variable doesn't match the one in my Terminal.
So when I execute
run('ls')
I get this:
/bin/sh: ls: command not found
Which makes sense because, nonsensically, the PATH I get from running
print run('/usr/bin/env')
is
PATH=/Library/Frameworks/Python.framework/Versions/Current/bin/
Now, I could remedy all this by using:
run('/bin/ls')
But that defeats the entire purpose of using this command, which is to faithfully emulate the bash
shell.
How do I make run() use the system's PATH or create an equivalent function that just works?
(No platitudes about the dangers of using 'shell=True'
, please. This is all personal use with innocuous commands like ls
and ps axw
.)
I'm leaving this question up because I think the run()
command above is useful and I couldn't find anything similar on SO.
However, my solution was very system specific. The problem was, I am running this script within Sublime Text 2 and had manually replaced the path in Python.sublime-settings
with
"path": "/Library/Frameworks/Python.framework/Versions/Current/bin/",
I did this because I'd had problems getting ST2 to find the right version of python
. Well, this also overwrites the system-wide PATH variable within ST2, thus blocking my access to simple shell programs like ls
.
Erasing the "path": ...
line from Python.sublime-settings
fixed my problem.
EDIT
As suggested by mklement0, changing the line to append the path works as well:
"path": "$PATH:/Library/Frameworks/Python.framework/Versions/Current/bin/",
这篇关于获取与Python的bash输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!