需要帮助处理包含bash命令的python脚本
我从网上复制了这个脚本,但我不知道怎么用。我是Python的新手,所以请帮帮我。当我用命令
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
这个脚本叫做“test.py”。你可以直接这样运行它,或者把它改名为“py4sa”。
0
你用解释器来运行一个Python脚本,所以你可以这样做:
$ python py4sa
2
看起来你把脚本存储在了另一个名字下:test.py,而不是py4sa。所以像你那样输入 ./test.py 是正确的。不过,这个程序需要一些参数,所以你得输入'usage'下列出的选项之一。
通常来说,'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里。它显示'usage: py4sa (..)'是因为这个信息是写死在程序里的。