简体   繁体   中英

Multithreading while calling shell commands from python

Suppose I am iteratively calling different bash commands with Python while my script is running. How would I do threading (or sleep) such that my Python script would not stall and stop? I tried using:

threading.Timer(5.0, self.func).start()

But maybe because my shell commands are complex the Python script/application stalls.

Example:

def func(self, command):
    cmd = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
    output, eff = cmd.communicate()
    return output

def __init__(self, parent=None):
    threading.Timer(5.0, self.func).start()
    command = "ifconfig"
    print self.func(command)

ps but I dont call "ifconfig" it is just an example

You're calling func twice. On the last line, you're calling it on the same thread you're standing. This is going to block until func returns.

You do not send command as parameter to your function while creating timer. I made a working example based on your code and here is how you run a timer with parameters. As @felipe-lema said, you are calling function twice and I did not change it in code although I did not understand the reason.

threading.Timer(interval, function, args=[], kwargs={})

#!/usr/bin/python2.7
import sys
import threading
import subprocess

class TestClass(object):

    def __init__(self, parent=None):
        command = "ifconfig"
        threading.Timer(5.0, self.func, (command,),).start()
        print self.func(command)

    def func(self, command):
        cmd = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
        output, eff = cmd.communicate()
        sys.stdout.write("In Thread "+threading.current_thread().name+"\n")
        sys.stdout.write(output)
        return output

TestClass()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM