Home > Software engineering >  How to implement bash oneliner into Python3 code?
How to implement bash oneliner into Python3 code?

Time:07-21

I have bash oneliner and I can't use implement it into python3 and running it on Rhel server.

 for i in {5000..10000}; do if grep "no such user" <(id $i 2>&1 ) > /dev/null; then echo $i ; break ; fi; done

I've already tried

print(subprocess.check_output('bash -c "for i in {5000..10000}; do if grep "no such user" <(id $i 2>&1 ) > /dev/null; then echo $i ; break ; fi ; done" ', shell=True).decode())

and this

p1 = Popen(["for i in {5000..10000}; do if grep "no such user" <(id $i 2>&1 ) > /dev/null; then echo $i ; break ; fi; done"], stdout=PIPE)

print p1.communicate()

Tried also this

command = '''
    for i in {5000..10000}
do
    if grep "no such user" <(id $i 2>&1 ) > /dev/null
    then echo $i
    break
    fi
done
'''
        uid = subprocess.run(command, capture_output=True, shell=True)

And I always get SyntaxError: invalid syntax or

CompletedProcess(args='\n    for i in {5000..10000}\ndo\n    if grep "no such user" <(id $i 2>&1 ) > /dev/null\n    then echo $i\n    break\n    fi\ndone\n', returncode=1, stdout=b'', stderr=b'/bin/sh: -c: line 3: syntax error near unexpected token `(\'\n/bin/sh: -c: line 3: `    if grep "no such user" <(id $i 2>&1 ) > /dev/null\'\n')

Can you please help me and say what am I doing wrong? I've lost countless hours of debugging it and hope on your help.

CodePudding user response:

While the better answer is to do this all in Python (which will be vastly more efficient), there's no reason you can't do it with a subprocess.

Use a triple-quoted raw string so your bash code is stored in a Python string without anything munging it:

#!/usr/bin/env python
import subprocess

bash_code=r'''
for i in {5000..10000}; do if grep "no such user" <(id "$i" 2>&1 ) > /dev/null; then echo "$i" ; break ; fi; done
'''
p = subprocess.run(['bash', '-c', bash_code], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(f"stdout is: {f.stdout}")

CodePudding user response:

Do the loop and output checking in Python.

for i in range(5000, 10001):
    output = subprocess.check_output(['id', str(i)], stderr=subprocess.DEVNULL, encoding='utf-8')
    if 'no such user' in output:
        print(i)
        break

Python also has a pwd module for searching the user database.

from pwd import getpwuid

for i in range(5000, 10001):
    try:
        getpwuid(i)
    except KeyError:
        print(i)
        break
  • Related