简体   繁体   中英

How to check if program is running by python script?

Now I have a udp_server.py to run.

According to my less experience, I will do a python script in crontab as bellow.

import commands
output = commands.getoutput("ps aux | grep udp_server.py")
'''print output 
user      8695  0.0  0.3  50948 14196 pts/0    S    10:21   0:00 python udp_server.py
user      9486  0.0  0.0   4400   584 pts/0    S+   10:34   0:00 sh -c {  ps aux | grep 'udp_server.py'; } 2>&1
user      9488  0.0  0.0   9384   888 pts/0    R+   10:34   0:00 grep udp_server.py
'''
if 'python udp_server.py' in output:
    print "The server is active."

is this right?

If you want to type command line as like typing in unix console, it's right.

Suppose you will package the code in a file, maybe you will encounter a problem: it can't excute command. It's because your account in linux hasn't enough authority, I suggest you do as the following:

sudo python command_file.py

By the way, if you really work in python2.6+, please notice the api, deprecated since version 2.6: The commands module has been removed in Python 3. Use the subprocess module instead. So I suggest you replace it form subprocess . Reference hypelink: commands

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