How to store the result of an executed shell command in a variable in python?

前端 未结 5 1694
执笔经年
执笔经年 2020-12-13 06:20

I need to store the result of a shell command that I executed in a variable, but I couldn\'t get it working. I tried like:

import os    

call = os.system(\"         


        
相关标签:
5条回答
  • 2020-12-13 07:11

    commands.getstatusoutput would work well for this situation. (Deprecated since Python 2.6)

    import commands
    print(commands.getstatusoutput("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'"))
    
    0 讨论(0)
  • 2020-12-13 07:11

    All the other answers here are fine answers. In many situations, you do need to run external commands.

    This specific example has another option: you can read the file, process it line by line, and do something with the output.

    While this answer doesn't work for the "more general question being asked", I think it should always be considered. It is not always the "right answer", even where possible. Remembering this (easier), and knowing when (not) to apply it (more difficult), will make you a better programmer.

    0 讨论(0)
  • 2020-12-13 07:21

    In python 3 you can use

    import subprocess as sp
    output = sp.getoutput('whoami --version')
    print (output)
    
    ``
    
    0 讨论(0)
  • 2020-12-13 07:24

    Use the subprocess module instead:

    import subprocess
    output = subprocess.check_output("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'", shell=True)
    

    Edit: this is new in Python 2.7. In earlier versions this should work (with the command rewritten as shown below):

    import subprocess
    output = subprocess.Popen(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'], stdout=subprocess.PIPE).communicate()[0]
    

    As a side note, you can rewrite

    cat syscall_list.txt | grep f89e7000
    

    To

    grep f89e7000 syscall_list.txt
    

    And you can even replace the entire statement with a single awk script:

    awk '/f89e7000/ {print $2}' syscall_list.txt
    

    Leading to:

    import subprocess
    output = subprocess.check_output(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'])
    
    0 讨论(0)
  • 2020-12-13 07:25

    os.popen works for this. popen - opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read. split('\n') converts the output to list

    import os
    list_of_ls = os.popen("ls").read().split('\n')
    print list_of_ls
    
    import os
    list_of_call = os.popen("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'").read().split('\n')
    print list_of_call
    
    0 讨论(0)
提交回复
热议问题