需要帮助python脚本与bash命令

时间:2011-05-01 04:41:26

标签: python linux bash

我从互联网上复制了这个脚本,但我不知道如何使用它。我是python的新手,所以请帮忙。当我使用它执行它 ./test.py然后我只能看到

usage: py4sa [option]

A unix toolbox

options:
  --version      show program's version number and exit
  -h, --help     show this help message and exit
  -i, --ip       gets current IP Address
  -u, --usage    gets disk usage of homedir
  -v, --verbose  prints verbosely

当我键入py4sa然后它说没有找到bash命令 完整的脚本是

#!/usr/bin/env python
import subprocess
import optparse
import re

#Create variables out of shell commands
#Note triple quotes can embed Bash

#You could add another bash command here
#HOLDING_SPOT="""fake_command"""

#Determines Home Directory Usage in Gigs
HOMEDIR_USAGE = """
du -sh $HOME | cut -f1
"""

#Determines IP Address
IPADDR = """
/sbin/ifconfig -a | awk '/(cast)/ { print $2 }' | cut -d':' -f2 | head -1
"""

#This function takes Bash commands and returns them
def runBash(cmd):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    out = p.stdout.read().strip()
    return out  #This is the stdout from the shell command

VERBOSE=False
def report(output,cmdtype="UNIX COMMAND:"):
   #Notice the global statement allows input from outside of function
   if VERBOSE:
       print "%s: %s" % (cmdtype, output)
   else:
       print output

#Function to control option parsing in Python
def controller():
    global VERBOSE
    #Create instance of OptionParser Module, included in Standard Library
    p = optparse.OptionParser(description='A unix toolbox',
                                            prog='py4sa',
                                            version='py4sa 0.1',
                                            usage= '%prog [option]')
    p.add_option('--ip','-i', action="store_true", help='gets current IP Address')
    p.add_option('--usage', '-u', action="store_true", help='gets disk usage of homedir')
    p.add_option('--verbose', '-v',
                action = 'store_true',
                help='prints verbosely',
                default=False)

    #Option Handling passes correct parameter to runBash
    options, arguments = p.parse_args()
    if options.verbose:
        VERBOSE=True
    if options.ip:
        value = runBash(IPADDR)
        report(value,"IPADDR")
    elif options.usage:
        value = runBash(HOMEDIR_USAGE)
        report(value, "HOMEDIR_USAGE")
    else:
        p.print_help()

#Runs all the functions
def main():
    controller()

#This idiom means the below code only runs when executed from command line
if __name__ == '__main__':
    main()

3 个答案:

答案 0 :(得分:2)

在我看来,您已将脚本存储在另一个名称下:test.py而不是py4sa。所以输入./test.py就像你一样,对你来说是对的。但是,该程序需要参数,因此您必须输入“使用”下列出的选项之一。

通常'py4sa [OPTIONS]'意味着OPTIONS是可选的,但是查看代码我们可以看到它不是:

if options.verbose:
    # ...
if options.ip:
    # ...
elif options.usage:
    # ...
else:
    # Here's a "catch all" in case no options are supplied. 
    # It will show the help text you get:
    p.print_help()

请注意,即使您将程序重命名为py4sa,bash也可能无法识别该程序,因为当前目录通常不在bash的PATH中。它说'用法:py4sa(..)',因为它被硬编码到程序中。

答案 1 :(得分:0)

该脚本名为“test.py”。要么像这样调用它,要么将其重命名为“py4sa”。

答案 2 :(得分:0)

使用解释器运行Python脚本,所以

$ python py4sa