If you want to handle shell commands in Python, you generally use the subprocess
module. It is possible to pass the result as a list by using stdout.readlines ()
in the module, but if the shell command to be executed spans multiple lines, the line feed code (line feed) will be passed together. Therefore, in order to pass the list with the line feed code (line feed) removed, the following processing should be performed.
Here, we will explain using an example of executing ls -l
from Python as a shell command.
This time, I created three scripts according to the following three ways.
Actually, the result sample when ls -l
is executed is as follows.
$ ls -l
total 12
-rwxr-xr-x 1 root root 260 Jun 16 18:48 res_cmd_lfeed.py
-rwxr-xr-x 1 root root 378 Jun 16 18:49 res_cmd_no_lfeed.py
-rwxr-xr-x 1 root root 247 Jun 16 18:48 res_cmd.py
Get the first array element of communicate ()
.
res_cmd.py
#!/usr/bin/python
import subprocess
def res_cmd(cmd):
return subprocess.Popen(
cmd, stdout=subprocess.PIPE,
shell=True).communicate()[0]
def main():
cmd = ("ls -l")
print(res_cmd(cmd))
if __name__ == '__main__':
main()
As shown below, the execution result of the script is the same as when ls -l
is executed.
$ ./res_cmd.py
total 12
-rwxr-xr-x 1 root root 260 Jun 16 18:48 res_cmd_lfeed.py
-rwxr-xr-x 1 root root 378 Jun 16 18:49 res_cmd_no_lfeed.py
-rwxr-xr-x 1 root root 247 Jun 16 18:48 res_cmd.py
Use stdout.readlines ()
.
res_cmd_lfeed.py
#!/usr/bin/python
import subprocess
def res_cmd_lfeed(cmd):
return subprocess.Popen(
cmd, stdout=subprocess.PIPE,
shell=True).stdout.readlines()
def main():
cmd = ("ls -l")
print(res_cmd_lfeed(cmd))
if __name__ == '__main__':
main()
You can get a list of results that include line feeds.
$ ./res_cmd_lfeed.py
['total 12\n', '-rwxr-xr-x 1 root root 261 Jun 16 18:52 res_cmd_lfeed.py\n', '-rwxr-xr-x 1 root root 380 Jun 16 18:52 res_cmd_no_lfeed.py\n', '-rwxr-xr-x 1 root root 248 Jun 16 18:51 res_cmd.py\n']
Use stdout.readlines ()
and rstrip ("\ n")
in list comprehensions.
res_cmd_no_lfeed.py
#!/usr/bin/python
import subprocess
def res_cmd_lfeed(cmd):
return subprocess.Popen(
cmd, stdout=subprocess.PIPE,
shell=True).stdout.readlines()
def res_cmd_no_lfeed(cmd):
return [str(x).rstrip("\n") for x in res_cmd_lfeed(cmd)]
def main():
cmd = ("ls -l")
print(res_cmd_no_lfeed(cmd))
if __name__ == '__main__':
main()
You can get a list of results excluding line feed.
$ ./res_cmd_no_lfeed.py
['total 12', '-rwxr-xr-x 1 root root 261 Jun 16 18:52 res_cmd_lfeed.py', '-rwxr-xr-x 1 root root 380 Jun 16 18:52 res_cmd_no_lfeed.py', '-rwxr-xr-x 1 root root 248 Jun 16 18:51 res_cmd.py']
Recommended Posts