python - 在使用 bash 命令的 python 脚本方面需要帮助

标签 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()

最佳答案

在我看来,您已将脚本存储在另一个名称下: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 (..)”,因为它已硬编码到程序中。

关于python - 在使用 bash 命令的 python 脚本方面需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5846494/

相关文章:

python - 如何使用 Kivy Clock.schedule_once 安排事件

python - Celery 如何处理链内的任务失败?

java - 如何阻止客户端监听服务器或客户端正在监听的端口

android - 运行与终端分离的 AVD 模拟器

linux - InfluxDB 使用 sensu 写性能统计

python - Numbapro : No speed-up for Matrix Multiplication

Panda Dataframe 的 Python 并发 Future

bash - 在两个分隔符之间提取多行数据

bash - 在 bash 脚本中建议对用户输入的回答

linux - 从文件中读取反向行