如何 运行 在 python 上执行 sh 脚本?

How to run sh scripts on python?

假设我有一个 python 程序并且我想执行这个

grep "username" accounts.txt

1 行

accounts.txt和我的py文件在同一个文件夹。我知道在 C 中有一些像 System(grep "username" accounts.txt) 的函数,我想知道 python 中是否有类似的东西。通常 python 读取 accounts.txt 太慢,因为它是一个大文件。但是在 bash 或 linux 中它要快得多,所以想知道我是否可以使用 bash 找到用户名行然后 python 打印出来。

如果有 none,集成大型用户名文件的有效方法是什么?我可以在我的 python 代码中调用它来打印与其关联的行。

使用commands module or subprocess模块执行命令。

注意:命令模块已从 python3 中删除。因此,如果您使用的是 python3,我建议使用 subprocess 模块,因为 python2 包含两个模块。

import os
os.system('grep username accounts.txt')

import subprocess
subprocess.call('grep username accounts.txt', shell=True)

应该有用..我没有用过很多但我知道(出于某种原因)使用子进程要好得多。

os.system('grep Hello test.txt')

输出:Hello World!

subprocess.call('grep Hello test.txt',shell=True)

输出:Hello World!