Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a UNIX command in Python script

Tags:

python

unix

#!/usr/bin/python

import os
import shutil
import commands
import time
import copy

name = 'test'

echo name 

I have a simple python scripts like the above. When I attempt to execute it I get a syntax error when trying to output the name variable.

like image 328
user1204195 Avatar asked May 27 '26 14:05

user1204195


2 Answers

You cannot use UNIX commands in your Python script as if they were Python code, echo name is causing a syntax error because echo is not a built-in statement or function in Python. Instead, use print name.

To run UNIX commands you will need to create a subprocess that runs the command. The simplest way to do this is using os.system(), but the subprocess module is preferable.

like image 141
Andrew Clark Avatar answered May 30 '26 04:05

Andrew Clark


you can also use subprocess module.

import subprocess
proc = subprocess.Popen(['echo', name],
                            stdin = subprocess.PIPE,
                            stdout = subprocess.PIPE,
                            stderr = subprocess.PIPE
                        )

(out, err) = proc.communicate()
print out

Read: http://www.doughellmann.com/PyMOTW/subprocess/

like image 28
pyfunc Avatar answered May 30 '26 03:05

pyfunc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!