简体   繁体   中英

Exiting an infinite process in python subprocess

i have the following code

c = open("text.txt", 'a')    

output = subprocess.Popen('ping -t 127.0.0.1', stdout=subprocess.PIPE).communicate()[0]

c.write(str(output))

But as the ping is infinite , the code stucks at line two till i close the cmd

how can i close the infinite subprocess

i use python 2

You can use -n argument (in linux) for ping to set limited number of ping signals:

process = subprocess.Popen('ping -n 1 127.0.0.1', shell=True, stdout=subprocess.PIPE)
output = process.communicate()[0]
with open("text.txt", 'a') as f:
    f.write(str(output))

Or read a single first line only:

process = subprocess.Popen('ping 127.0.0.1', shell=True, stdout=subprocess.PIPE, universal_newlines=True)

output = process.stdout.readline()
process.stdout.close()
process.kill()

with open("text.txt", 'a') as f:
    f.write(str(output))

Alternatively you can use check_output and add a timeout :

from subprocess import check_output

output = check_output('ping -t 127.0.0.1', timeout=seconds)
process = subprocess.Popen('ping -t 127.0.0.1', stdout=subprocess.PIPE)
time.sleep(10)
process.kill()
output=process.stdout.read()

with this code , subprocess runs and data will be given stdout,

we don't need to use communicate

when ever you want to stop the process,

use process.kill()

and get data using stdout.read()

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