【发布时间】:2013-11-25 01:54:14
【问题描述】:
我有一个 Python 脚本,它在从命令行运行脚本时将命令行参数分配给不同的变量。我以前做过这个,几乎没有问题,但这次我被一些似乎有点技术性的东西挂断了,我不能轻易解决。
假设我在开头附近有以下语句:
n_value = sys.argv[3]
我期望的命令行参数是一个整数字符串,从 1 到 6。然后,稍后,我想测试 n_value 指向的值,以确定下一步要走的路。所以,我有以下几点:
if n_value == "1":
(do something)
最后,对于不期望命令行参数输入的实例,有一个 else 语句。每次我尝试运行程序时都会得到这个。我尝试将 if 语句更改为:
if n_value == 1:
或者:
if n_value is "1"
等等。我已经尝试了很多东西,但我似乎无法实现该值。
我也尝试使用 pdb,在这些语句之前使用 set_trace()。在调试器中,我尝试查看表达式 n_value == "1" 的值,它显示为“True”。这让我相信这可能是我正在使用的版本的一些技术问题(即,我做错了什么但我没有意识到)或者我只是不了解 Python 等价的来龙去脉操作。
最后一点:我一直使用的 Python 版本是 2.6 和 2.7。据我所知,两者都存在同样的问题。
如果有兴趣,请看下面我的 main() 方法的开头:
def main():
if len(sys.argv) != 4:
print(r'usage: python(2.6) ./log_likelihood_ngrams.py /path/to/input_file1 /path/to/input_file2 n_value')
sys.exit(1)
# Store command-line arguments as variables
input_file1_path = sys.argv[1]
input_file2_path = sys.argv[2]
n_value = sys.argv[3]
# Tokenize the input files and save their n-grams in n-gram-lists
# For 1-grams
if n_value == '1':
ngrams_list1 = tokenize(input_file1_path)
ngrams_list2 = tokenize(input_file2_path)
# For 2-grams
if n_value == '2':
ngrams_list1 = bigram_list(input_file1_path)
ngrams_list2 = bigram_list(input_file2_path)
# For 3-grams
if n_value == '3':
ngrams_list1 = trigram_list(input_file1_path)
ngrams_list2 = trigram_list(input_file2_path)
# For 4-grams
if n_value == '4':
ngrams_list1 = four_gram_list(input_file1_path)
ngrams_list2 = four_gram_list(input_file2_path)
# For 5-grams
if n_value == '5':
ngrams_list1 = five_gram_list(input_file1_path)
ngrams_list2 = five_gram_list(input_file2_path)
# For 6-grams
if n_value == '6':
ngrams_list1 = six_gram_list(input_file1_path)
ngrams_list2 = six_gram_list(input_file2_path)
# If n is invalid, print an error message and exit the program.
else:
sys.stderr.write('\n\nThe value of n you entered is not valid!\nPlease enter a value between 1 and 6, inclusive.\n')
sys.exit(1)
【问题讨论】:
-
您是否检查过您是否尝试比较不同的编码?另外,你试过 str(1) 吗?
-
打印
repr(nvalue)。这将揭示答案:-) -
@VikramSaran 是的,我有。我尝试将初始分配更改为 n_value = str(sys.argv[3]) 和 n_value = sys.argv 后跟 n_value = str(n_value) (只是因为我之前遇到过对实际 sys.argv 方法进行类型转换的问题)。我还尝试使用 int() 进行类型转换并将值更改为实际整数,而不是这些整数的字符串。
标签: python python-2.7 python-2.6