社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python上运行sh脚本?

ss sss • 5 年前 • 1535 次点击  

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

grep "username" accounts.txt

一行

accounts.txt与我的py文件位于同一文件夹中。我知道在C中有一些类似System的函数(grep“username”accounts.txt),我想知道在Python中是否有类似的函数。通常python太慢,无法读取accounts.txt,因为它是一个大文件。但是在bash或linux中要快得多,所以想知道是否可以使用bash来查找用户名行,然后python将其打印出来。

如果没有,那么有什么方法可以有效地集成一个包含用户名的大文件,我可以在python代码中调用它来打印出与之相关的行。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39621
 
1535 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Yogaraj
Reply   •   1 楼
Yogaraj    5 年前

使用 commands 模块或 subprocess 执行命令的模块。

注意:命令模块已从python3中删除。所以,如果您使用python3,我建议您使用subprocess模块,因为python2同时拥有这两个模块。

Derek Eden
Reply   •   2 楼
Derek Eden    5 年前
import os
os.system('grep username accounts.txt')

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

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

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

输出:你好世界!

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

输出:你好世界!