简体   繁体   English

Python命令行参数(Windows)

[英]Python Command Line Arguments (Windows)

I am running 32-bit Windows 7 and Python 2.7. 我正在运行32位Windows 7和Python 2.7。

I am trying to write a command line Python script that can run from CMD. 我正在尝试编写一个可以从CMD运行的命令行Python脚本。 I am trying to assign a value to sys.argv[1]. 我正在尝试为sys.argv [1]分配一个值。 The aim of my script is to calculate the MD5 hash value of a file. 我的脚本的目的是计算文件的MD5哈希值。 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. 在命令行中调用脚本时将输入此文件,因此,sys.argv [1]应表示要进行哈希处理的文件。

Here's my code below: 这是我的代码如下:

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

To call my script, I have been writing "script.py test.txt" for example. 为了调用我的脚本,我一直在编写“script.py test.txt”。 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. 我测试了len(sys.argv),它只返回包含一个值,即python脚本名称。

Any suggestions? 有什么建议? I can only assume it is how I am invoking the code through CMD 我只能假设我是通过CMD调用代码的

You should check that in your registry the way you have associated the files is correct, for example: 您应该在注册表中检查与文件关联的方式是否正确,例如:

[HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command]
@="\"C:\\Python27\\python.exe\" \"%1\" %*"

The problem is in the registry. 问题出在注册表中。 Calling python script.py test.txt works, but this is not the solution. 调用python script.py test.txt有效,但这不是解决方案。 Specially if you decide to add the script to your PATH and want to use it inside other directories as well. 特别是如果您决定将脚本添加到PATH并希望在其他目录中使用它。

Open RegEdit and navigate to HKEY_CLASSES_ROOT\\Applications\\python.exe\\shell\\open\\command. 打开RegEdit并导航到HKEY_CLASSES_ROOT \\ Applications \\ python.exe \\ shell \\ open \\ command。 Right click on name (Default) and Modify. 右键单击名称(默认)和修改。 Enter: 输入:

"C:\Python27\python.exe" "%1" %*

Click OK, restart your CMD and try again. 单击“确定”,重新启动CMD,然后重试。

尝试使用python script.py test.txt运行该脚本,您可能会将解释器与.py扩展名关联起来。

Did you try sys.argv[0] ? 你试过sys.argv[0]吗? If len(sys.argv) = 0 then sys.argv[1] would try to access the second and nonexistent item 如果len(sys.argv) = 0sys.argv[1]将尝试访问第二个且不存在的项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM