Python Script execute commands in Terminal

前端 未结 9 1650
余生分开走
余生分开走 2020-11-29 16:51

I read this somewhere a while ago but cant seem to find it. I am trying to find a command that will execute commands in the terminal and then output the result.

For

相关标签:
9条回答
  • 2020-11-29 17:09

    Jupyter

    In a jupyter notebook you can use the magic function !

    !echo "execute a command"
    files = !ls -a /data/dir/ #get the output into a variable
    

    ipython

    To execute this as a .py script you would need to use ipython

    files = get_ipython().getoutput('ls -a /data/dir/')
    

    execute script

    $ ipython my_script.py
    
    0 讨论(0)
  • 2020-11-29 17:17

    There are several ways to do this:

    A simple way is using the os module:

    import os
    os.system("ls -l")
    

    More complex things can be achieved with the subprocess module: for example:

    import subprocess
    test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
    output = test.communicate()[0]
    
    0 讨论(0)
  • 2020-11-29 17:21

    You should also look into commands.getstatusoutput

    This returns a tuple of length 2.. The first is the return integer ( 0 - when the commands is successful ) second is the whole output as will be shown in the terminal.

    For ls

        import commands
        s=commands.getstatusoutput('ls')
        print s
        >> (0, 'file_1\nfile_2\nfile_3')
        s[1].split("\n")
        >> ['file_1', 'file_2', 'file_3']
    
    0 讨论(0)
提交回复
热议问题