Launch a shell command with in a python script, wait for the termination and return to the script

后端 未结 7 489
失恋的感觉
失恋的感觉 2020-11-28 22:09

I\'ve a python script that has to launch a shell command for every file in a dir:

import os

files = os.listdir(\".\")
for f in files:
    os.execlp(\"myscri         


        
相关标签:
7条回答
  • 2020-11-28 22:45

    I use os.system

    import os
    os.system("pdftoppm -png {} {}".format(path2pdf, os.path.join(tmpdirname, "temp")))
    
    0 讨论(0)
  • 2020-11-28 22:53

    The subprocess module has come along way since 2008. In particular check_call and check_output make simple subprocess stuff even easier. The check_* family of functions are nice it that they raise an exception if something goes wrong.

    import os
    import subprocess
    
    files = os.listdir('.')
    for f in files:
       subprocess.check_call( [ 'myscript', f ] )
    

    Any output generated by myscript will display as though your process produced the output (technically myscript and your python script share the same stdout). There are a couple of ways to avoid this.

    • check_call( [ 'myscript', f ], stdout=subprocess.PIPE )
      The stdout will be supressed (beware if myscript produces more that 4k of output). stderr will still be shown unless you add the option stderr=subprocess.PIPE.
    • check_output( [ 'myscript', f ] )
      check_output returns the stdout as a string so it isnt shown. stderr is still shown unless you add the option stderr=subprocess.STDOUT.
    0 讨论(0)
  • 2020-11-28 22:57

    You can use subprocess.Popen. There's a few ways to do it:

    import subprocess
    cmd = ['/run/myscript', '--arg', 'value']
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    for line in p.stdout:
        print line
    p.wait()
    print p.returncode
    

    Or, if you don't care what the external program actually does:

    cmd = ['/run/myscript', '--arg', 'value']
    subprocess.Popen(cmd).wait()
    
    0 讨论(0)
  • 2020-11-28 23:02

    this worked for me fine!

    shell_command = "ls -l" subprocess.call(shell_command.split())

    0 讨论(0)
  • 2020-11-28 23:05

    subprocess: The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

    http://docs.python.org/library/subprocess.html

    Usage:

    import subprocess
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
    process.wait()
    print process.returncode
    
    0 讨论(0)
  • 2020-11-28 23:05

    The os.exec*() functions replace the current programm with the new one. When this programm ends so does your process. You probably want os.system().

    0 讨论(0)
提交回复
热议问题