0

Is there a way for the Python print statement containing a bash command to run in the terminal directly from the Python script?

In the example below, the awk command is printed on the terminal.

#!/usr/bin/python
import sys

print "awk 'END{print NF}' file"

I can of course think of writing the print statement in a separate file and run that file as a bash script but is there a way to run the awk command directly from the python script rather than just printing it?

Homap
  • 2,142
  • 5
  • 24
  • 34
  • 4
    Why would you write a Python script for that? Either write the functionality in Python or just write a shell script. – jonrsharpe May 28 '17 at 12:01

3 Answers3

2

You can pipe your Python output into a Bash process, for example,

python -c "print 'echo 5'" | bash

will output

5

You could even use the subprocess module to do that from inside Python, if you wanted to.

But I am sure this is pretty bad design, and not a good idea. If you get your coding wrong, there's a risk you could allow hostile users to execute arbitrary commands on the machine running your code.

jdpipe
  • 232
  • 1
  • 11
2

is there a way to run the awk command directly from the python script rather than just printing it?

Yes, you can use subprocess module.

import subprocess
subprocess.call(["ls", "-l"])
gzc
  • 8,180
  • 8
  • 42
  • 62
1

One solution is to use subprocess to run a shell command and capture its output, for example:

import subprocess

command = "awk 'END{print NF}' file"
p = subprocess.Popen([command], shell=True, bufsize=2000,
    stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
(child_stdout, child_stdin) = (p.stdout, p.stdin)
print(''.join([line for line in child_stdout]))

child_stdout.close()
p.stdout.close()

Adjust bufsize accordingly based on the size of your file.

R Gowin
  • 11
  • 1
  • 4