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

查看:39
本文介绍了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)

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

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天全站免登陆