简体   繁体   English

来自python内部的bash命令

[英]bash commands from within python

I'm looking for the best way to use bash commands from within python. 我正在寻找在python中使用bash命令的最佳方法。 What ways are there? 有什么办法? I know of os.system and subprocess.Popen. 我知道os.system和subprocess.Popen。

I have tried these: 我已经尝试过这些:

bootfile = os.system("ls -l /jffs2/a.bin | cut -d '/' -f 4")
print bootfile

This returns a.bin as expected but also it retuns 0 afterwards and so prints: 这将按预期返回a.bin,但之后也会调整为0,因此输出:

a.bin
0

with bootfile now being set to 0. The next time I print bootfile it just shows up as 0. Which is the exit value I guess, how do i stop this value interfering? 引导文件现在设置为0。下一次我打印引导文件时,它将显示为0。我猜这是退出值,如何停止该值的干扰?

I have also tried: 我也尝试过:

bootfile = subprocess.Popen("ls -l /jffs2/a.bin | cut -d '/' -f 4")
print bootfile

but it seems to break the script, as in I get nothing returned at all, have I done that right? 但这似乎破坏了脚本,因为我什么也得不到,我做对了吗?

Also which of these is better and why? 还有哪个更好,为什么呢? Are there other ways and what is the preferred way? 还有其他方法,首选的方法是什么?

使用os.readlink (由@kojiro提出)和os.path.basename仅获取名称文件:

os.path.basename(os.readlink('/jffs2/a.bin'))

kojiro's comment about os.readlink is probably what you want. 小次郎的有关评论os.readlink可能是你想要的东西。 I am explaining what you were trying to implement. 我正在解释您要实施的内容。

os.system would return you exit status of the command run. os.system将返回命令运行的退出状态。

subprocess.Popen will create a pipe, so that you can capture the output of the command run. subprocess.Popen将创建一个管道,以便您可以捕获命令运行的输出。
Below line will capture output of the command run: 下面的行将捕获命令运行的输出:

bootfile = subprocess.Popen(["bash","-c","ls -l /jffs2/a.bin | cut -d '/' -f 4"], stdout=subprocess.PIPE).communicate()[0]

More details at http://docs.python.org/library/subprocess.html 有关更多详细信息,请参见http://docs.python.org/library/subprocess.html

The right answer, as @kojiro says, is: 如@kojiro所说,正确的答案是:

os.readlink('/jffs2/a.bin')

But if you really wanted to do this the complicated way, then in Python 2.7: 但是,如果您真的想以复杂的方式执行此操作,则在Python 2.7中:

cmd = "ls -l /jffs2/a.bin | cut -d '/' -f 4"
bootfile = subprocess.check_output(cmd, shell=True)

Or on older Pythons: 或在较旧的Python上:

cmd = "ls -l /jffs2/a.bin | cut -d '/' -f 4"
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
bootfile = p.communicate()[0]
if p.returncode != 0:
    raise Exception('It failed')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM