How do I create a subprocess in Python?

后端 未结 6 1545
孤独总比滥情好
孤独总比滥情好 2021-01-18 09:21

I would like to create a subprocess of a process.

What would be a working example which shows how to accomplish this?

相关标签:
6条回答
  • 2021-01-18 09:58
    if os.name == 'nt':
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
    subprocess.call(os.popen(tempFileName), shell=True)
    os.remove(tempFileName)
    
    0 讨论(0)
  • 2021-01-18 10:11

    Launching and monitoring a subprocess:

    import subprocess, time, os, signal
    args=['/usr/bin/vmstat','-n','2']
    app=subprocess.Popen(args=args, stdout=open('somefile','w'))
    print "Your app's PID is %s. You can now process data..." % app.pid
    time.sleep(5)
    if app.poll() == None: print "Process is still running after 5s."
    print "The app outputed %s bytes." % len(open('somefile','r').read())
    print "Stopping the process..."
    os.kill(app.pid, signal.SIGTERM)
    

    There is more to it. Just check the Popen docs.

    0 讨论(0)
  • 2021-01-18 10:13

    Based on user225312's answer, I prepared the below one liner, it may help you to test the subprocess:

    python -c "import subprocess;
    output = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE).communicate()[0]; 
    print output"
    

    result like: Linux xxx.xxx.xxx.xxx 3.10.0-957.1.3.el7.x86_64 #1 SMP Thu Nov 29 14:49:43 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

    0 讨论(0)
  • 2021-01-18 10:22

    Start with the subprocess documentation.

    If you want to get the output:

    >>> import subprocess
    >>> output = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE).communicate()[0]
    >>> output
    'Linux'
    

    If you just want to call and not deal with the output:

    >>> subprocess.call(['echo', 'Hi'])
    Hi
    0
    

    subprocess.check_call is the same except that it throws up a CalledProcessError in case the command is called with invalid parameters.

    A good subprocess tutorial.

    0 讨论(0)
  • 2021-01-18 10:23

    This is what worked for me if you want to run a simple command instead of giving a seperate file

    import subprocess
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
    process.wait()
    print process.returncode
    

    To get returncode of process you can use process.returncode To get response you can use process.communicate()

    in case if you are confuse you can just test this code by using command="ls"

    if you are getting returncode other than 0 then you can check here what that error code means: http://tldp.org/LDP/abs/html/exitcodes.html

    For more details about Subprocess: http://docs.python.org/library/subprocess.html

    0 讨论(0)
  • 2021-01-18 10:25
    import subprocess
    
    subprocess.call(['echo', 'hello world'])
    
    0 讨论(0)
提交回复
热议问题