简体   繁体   中英

How to run sh scripts on python?

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.

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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