I wrote the following code, expecting that the print information can be continuously output in for, but there is actually no output.
import salt.client
selector = "test"
client = salt.client.LocalClient()
def start_job(selector):
return client.run_job(selector, "cmd.run", arg=["""for i in {1..50}; do echo "Log line $i at $(date '+%T')"; sleep 1; done"""])
def check_job(job):
returned = client.get_cli_returns(job["jid"], job["minions"], timeout=30, verbose=True, show_jid=True)
print(list(returned))
for resp in returned:
print(f"Response: {resp}")
if __name__ == "__main__":
print("Immediate check -- fails")
job = start_job(selector)
print(job)
check_job(job)
In my expectation, it should continue to output the following
Response: Log line 1 at 11:47:08
Response: Log line 2 at 11:47:09
Response: Log line 3 at 11:47:10
Response: Log line 4 at 11:47:11
Response: Log line 5 at 11:47:12
Response: Log line 6 at 11:47:13
Response: Log line 7 at 11:47:14
....
In my expectation, it should continue to output the following content, or in other words, how to use the Python client API to implement the command execution process and pass it to the web page?
your expectation is wrong. salt is an async system. that and your output is printing that out to the console of the minion, NOT your salt client. a minion will not send anything back to the master until it is done running what ever command you sent it. in this case since your command is a shell script that will loop for 50 cycles printing out what you expected. until it actually finishes that loop it will send nothing back.
salt doesn't have a mechanism to watch running jobs. you can send out find_job to minions to see if they are still running. but that is about all.
once minions finish with the task they will send the return. and your check_job will start printing stuff. but with that sleep in the loop it is going to take at least 50 seconds before anything shows up.