python - 使用 Python 的 sys.argv 将函数结果返回到命令行?

标签 python linux arguments command-line-arguments

我有一个可执行的文件。它有一个功能,我想将其结果返回到命令行,但是,我不断收到 NameError 消息。为了分解,我正在使用 LinuxMint Lisa,到目前为止我有:

#! /usr/bin/env python
import mechanize
from BeautifulSoup import BeautifulSoup
import sys

def dictionary(word):
    br = mechanize.Browser()
    response = br.open('http://www.dictionary.reference.com')
    br.select_form(nr=0)
    br.form['q'] = word
    br.submit()
    definition = BeautifulSoup(br.response().read())
    trans = definition.findAll('td',{'class':'td3n2'})
    fin = [i.text for i in trans]
    query = {}
    for i in fin:
        query[fin.index(i)] = i
    return query

print dictionary(sys.argv)

然后我从我的终端 chmod:

sudo chmod +x this_file.py

当我从命令行调用这个文件时,我将输入:

./this_file.py 'pass'(or any other string argument)

哪个会返回:

TypeError: Must assign a string

所以我知道我显然没有正确使用 sys.argv,但是,当我试图将此函数结果返回到命令行时,我感觉我正在搞砸其他事情。

最佳答案

好吧,我不妨将此作为我的答案发布,而不仅仅是评论:

print dictionary(agrv)

argv 拼写错误。

应该是

print dictionary(sys.argv)

此外,使用 sys.argvargv 本身是不够的

关于python - 使用 Python 的 sys.argv 将函数结果返回到命令行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11925813/

相关文章:

python - 如何在一个 NumPy 数组中搜索位置,以便在这些位置获取第二个 NumPy 数组中的值?

linux - 从文件中的条目生成范围

python - 普通参数与关键字参数

c# - 传递数组作为参数

python - python3 翻转二进制字符串

python - 运行时错误: Working outside of application context with Celery and Flask in Python

python - 为什么这种递归不会超出递归限制

c++ - 创建共享对象时,不能使用针对符号 `ff_a64_muxer' 的重定位 R_X86_64_32;使用 -fPIC 重新编译

c - 笔记本电池状态?

Javascript:转发采用可变数量参数的函数调用