Python命令行参数(Windows) [英] Python Command Line Arguments (Windows)

查看:180
本文介绍了Python命令行参数(Windows)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行32位Windows 7和Python 2.7。

I am running 32-bit Windows 7 and Python 2.7.

我试图编写一个可以从CMD运行的命令行Python脚本。我试图分配一个值到sys.argv [1]。我的脚本的目的是计算文件的MD5哈希值。这个文件将在脚本在命令行中被调用时被输入,因此,sys.argv [1]应该代表要被哈希处理的文件。

I am trying to write a command line Python script that can run from CMD. I am trying to assign a value to sys.argv[1]. The aim of my script is to calculate the MD5 hash value of a file. This file will be inputted when the script is invoked in the command line and so, sys.argv[1] should represent the file to be hashed.

import sys
import hashlib

filename = sys.argv[1]

def md5Checksum(filePath):
    fh = open(filePath, 'rb')
    m = hashlib.md5()
    while True:
        data = fh.read(8192)
        if not data:
            break
        m.update(data)
    return m.hexdigest()

# print len(sys.argv)
print 'The MD5 checksum of text.txt is', md5Checksum(filename)


$ b b

每当我运行此脚本时,我收到一个错误:

Whenver I run this script, I receive an error:

filename = sys.argv[1]
IndexError: list index out of range

要调用我的脚本,我一直在写script.py test.txt。脚本和源文件都在同一目录中。我测试了len(sys.argv),它只返回包含一个值,这是python脚本名称。

To call my script, I have been writing "script.py test.txt" for example. Both the script and the source file are in the same directory. I have tested len(sys.argv) and it only comes back as containing one value, that being the python script name.

有任何建议吗?我只能假设它是如何我通过CMD

Any suggestions? I can only assume it is how I am invoking the code through CMD

推荐答案

调用代码尝试使用 python script.py test.txt ,您可能与解释器与 .py 扩展关联不良。

try to run the script using python script.py test.txt, you might have a broken association of the interpreter with the .py extention.

这篇关于Python命令行参数(Windows)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆