在python程序

时间:2016-06-15 09:09:37

标签: python linux ubuntu subprocess

可执行程序代码旨在在ubuntu中制作类似Windows的电源选项。这将针对'init 0'或'init 6'为每个用户运行,但对于'shutdown'和'reboot',它需要用户为root。我已经尝试使用getpass和shlex更改为root但它无法正常工作......

#!/usr/bin/python

import os
import subprocess
import shlex
import getpass


a = 0
#b = 1
#c = 2
#d = 3
#e = 4

while a == 0:
    os.system("tput setaf 2")
    print '\n\n\t**************************************************************\n'
    os.system("tput sgr 0 1")
    print '\t\t\tWelcome to Nitin\'s PowerHouse\n'
    os.system("tput sgr 0 0")
    os.system("tput setaf 2")
    print '\t**************************************************************\n'
    os.system("tput setaf 7")
    print '\t\tEnter 1: for normal shutdown...\n'
    print '\t\tEnter 2: for normal reboot...\n'
    print '\t\tEnter 3: for fast shutdown...\n'
    print '\t\tEnter 4: for fast reboot...\n'
    print '\t\tEnter 5: for suspending...\n\n'

    os.system("tput setaf 3")
    a = int (raw_input ('\t\tEnter the option for power buttons: '))
    if a == 1:
        print "This script was called by: "+getpass.getuser()
        print "Now do something as 'root'..."
        subprocess.call(shlex.split('sudo id -nu'))
        os.system('shutdown')
        break 
    elif a == 2:
        os.system('reboot')
        break
    elif a == 3:
        os.system('init 0')
        break
    elif a == 4:
        os.system('init 6')
        break
    elif a == 5:
        print "This script was called by: "+getpass.getuser()
        print "Now do something as 'root'..."
        subprocess.call(shlex.split('sudo id -nu'))
        os.system('pm-suspend')
        #print "Now switch back to the calling user: "+getpass.getuser()
        #os.system('pm-suspend')
        break
    else: 
        os.system("tput setaf 1")       
        print '\n\t\tEnter a correct choice'

os.system("tput setaf 7")
raw_input('\n\t\tPress Enter to leave now...')

程序中没有错误,但它不适用于输入的选项1:

    Must be root.

并且对于选项5,它说:

    Enter the option for power buttons: 5
    This script was called by: nitin
    Now do something as 'root'...
    [sudo] password for nitin: 
    root
    This utility may only be run by the root user.

    Press Enter to leave now...

0 个答案:

没有答案