Uros Simic
Uros Simic

Reputation: 21

Python variables and subprocess.call

First of all I would like to say that I am new to this website and any criticism is appreciated.

I am trying to modify a Python script to read an rfid key and then pipe the variable UID to a script (bash) that will authenticate it etc. So far I have managed to isolate the UID and I can print it in python but I can't get it in the bash script.

 print "" + str(uid[0]) + "" + str(uid[1]) + ""+ str(uid[2]) + "" + str(uid[3]) 

Here is the string I use to print the uid, how can I pipe that to a bash script? Thanks!

Upvotes: 2

Views: 387

Answers (1)

steffen
steffen

Reputation: 8968

Use the subprocess module:

import subprocess

uid = str(uid[0]) + str(uid[1]) + str(uid[2]) + str(uid[3])
result = subprocess.run(['check.sh', uid], stdout=subprocess.PIPE)
print(result.stdout)

If you use a python version prior to 3.5, instead of run you have to use call.

For this to work, the bash program must accept the uid as command line argument. If you need to pipe the string to the bash script, some more work is necessary:

import subprocess
import io
import tempfile

uid = str(uid[0]) + str(uid[1]) + str(uid[2]) + str(uid[3])

f = tempfile.TemporaryFile(mode='w+t')
f.write(uid)
f.seek(0)

result = subprocess.run(['check.sh', uid], stdin=f,  stdout=subprocess.PIPE)

f.close()

print(result.stdout)

Read https://docs.python.org/3/library/subprocess.html for further insights.

The interface has changed quiet a bit, so be aware of your Python Version. 2.x works differently than 3.4 than 3.5. There are compatible ways though.

Upvotes: 1

Related Questions