user1376294
user1376294

Reputation: 83

How to use subprocess module in python

What should I do if I want to call command like terminal(ubuntu) from python 2.7 so I want to use nfc-mfclassic which it able to use in terminal of ubuntu...Someone can help me to use that in python please..

I run this thing :nfc-mfclassic r a dumptest.mfd in terminal (Ubuntu)

Usage: nfc-mfclassic r|w a|b <dump.mfd> [<keys.mfd>]
  r|w           - Perform read from (r) or write to (w) card
  a|b           - Use A or B keys for action
  <dump.mfd>    - MiFare Dump (MFD) used to write (card to MFD) or (MFD to card)
  <keys.mfd>    - MiFare Dump (MFD) that contain the keys (optional)
Or: nfc-mfclassic x <dump.mfd> <payload.bin>
  x             - Extract payload (data blocks) from MFD
  <dump.mfd>    - MiFare Dump (MFD) that contains wanted payload
  <payload.bin> - Binary file where payload will be extracted

Upvotes: 1

Views: 2433

Answers (2)

aifarfa
aifarfa

Reputation: 3939

>>> import subprocess
>>> command = raw_input()
nfc-mfclassic r a dumptest.mfd

p = subprocess.Popen(command)

command is exactly what you typed in shell cmdline. the hard part is to properly format command text.

ref: http://docs.python.org/library/subprocess.html#module-subprocess

Upvotes: 0

Paulo Scardine
Paulo Scardine

Reputation: 77369

You can use subprocess directly, but there are a couple of very good subprocess wrappers that will make your life a lot easier.

I like PBS:

PBS is a unique subprocess wrapper that maps your system programs to Python functions dynamically. PBS helps you write shell scripts in Python by giving you the good features of Bash (easy command calling, easy piping) with all the power and flexibility of Python.

Example:

import pbs
print pbs.nfc_mfclassic("r", "a", "dumptest.mfd")

If you want to deal with an iterative application, perhaps you should look for something like pyexpect:

# This connects to the openbsd ftp site and
# downloads the recursive directory listing.
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('[email protected]')
child.expect ('ftp> ')
child.sendline ('cd pub')
child.expect('ftp> ')
child.sendline ('get ls-lR.gz')
child.expect('ftp> ')
child.sendline ('bye')

Upvotes: 1

Related Questions