0

Say I have a python program and I want to perform this

grep "username" accounts.txt

in 1 line

accounts.txt is in the same folder as my py file. I know in C there is some function like System(grep "username" accounts.txt) and would work wondering if there something like that in python. Normally python is too slow to read accounts.txt since its a large file. However in bash or linux its much faster, so wondering if I can use bash to find a username line then python prints it out.

If there is none, what would be an efficient way to integrate a large file of usernames that I can call on in my python code to print out the line associated with it.

ss sss
  • 75
  • 7
  • For making system calls take a look at https://stackoverflow.com/questions/89228/calling-an-external-command-in-python#89243 – user8977154 Sep 08 '19 at 02:56

2 Answers2

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

or

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

should work..I haven't used this alot but I know (for some reason) using subprocess is much better.

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

output: Hello World!

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

output: Hello World!

Derek Eden
  • 4,403
  • 3
  • 18
  • 31
0

Use the commands module or subprocess module to execute commands.

Note: Commands module has been removed from python3. So, if you're using python3 I would suggest to use the subprocess module where as python2 has both the modules.

Yogaraj
  • 322
  • 1
  • 4
  • 17