Python os.system without the output

后端 未结 4 1543
醉酒成梦
醉酒成梦 2020-12-16 11:24

I\'m running this:

os.system(\"/etc/init.d/apache2 restart\")

It restarts the webserver, as it should, and like it would if I had run the c

4条回答
  •  甜味超标
    2020-12-16 11:32

    Here is a system call function I pieced together several years ago and have used in various projects. If you don't want any output from the command at all you can just say out = syscmd(command) and then do nothing with out.

    Tested and works in Python 2.7.12 and 3.5.2.

    def syscmd(cmd, encoding=''):
        """
        Runs a command on the system, waits for the command to finish, and then
        returns the text output of the command. If the command produces no text
        output, the command's return code will be returned instead.
        """
        p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT,
            close_fds=True)
        p.wait()
        output = p.stdout.read()
        if len(output) > 1:
            if encoding: return output.decode(encoding)
            else: return output
        return p.returncode
    

提交回复
热议问题