Running a backquote shell in python?

I am translating bash scripts in python for some reason.

Python is more powerful, however, it is much more difficult to encode simple bash code as follows:

MYVAR = `grep -c myfile` 

With python, I must first define the backquote function:

 def backquote(cmd,noErrorCode=(0,),output=PIPE,errout=PIPE): p=Popen(cmd, stdout=output, stderr=errout) comm=p.communicate() if p.returncode not in noErrorCode: raise OSError, comm[1] if comm[0]: return comm[0].rstrip().split('\n') 

It's boring!

Is there a taste of Python (IPython?) Where it is easy to process the process and return the result?

+4
source share
4 answers

In Python 2.7 or higher, there is subprocess.check_output() , which basically does what you need.

+8
source

The os.subprocess documentation describes how to replace backquotes:

 output=`mycmd myarg` ==> output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] 
+4
source

backquote defining this backquote function, you can simply repeat it again and again, from your programs, as well as the interactive shell (IPython, etc.).

There is no direct way to use such "backquotes" in Python and IMHO for a good reason. Python is known for its readability, and having such a construct in the language encourages unreadable "script" code. Having said that backquote is probably not the most descriptive name for a function that returns subprocess output.

+2
source

As Andrea said, you should use subprocess.Popen - However, there is no need for advanced text input. You can do this in a separate file, say, "helper.py", which you import into your scripts:

 from subprocess import Popen, PIPE def r(cmd_line): return Popen(cmd_line.split(), stdout=PIPE).communicate()[0] 

And in other files you can only do

 from helper import r print r("ls -l") print r("pwd") r("tar czvf new_tarball.tar.gz %s" % path_to_archive) 

Note that this simplified method will not work if you need to go through a space inside the shell command parameter - like the "My Documents" parameter - in this case either use Popen explicitly or improve the helper function, so that it can handle it. Highlighting a white space with "\" will be ignored by the split that I use there.

0
source

Source: https://habr.com/ru/post/1344593/


All Articles