Skip to main content
 首页 » 编程设计

python之强制用python exe启动python脚本解析参数

2025年05月04日14bhlsheji

我在启动 python 脚本和获取发送到脚本的参数时遇到问题。

如您所见,如果我使用 python 命令启动以下测试脚本,它会工作,如果没有,那么,没有参数传递给脚本:/

import optparse 
import sys 
 
oOptParse = optparse.OptionParser() 
 
oOptParse.add_option("--arg", dest="arg", help="Test param") 
oOptParse.set_default("arg", None) 
 
if len(sys.argv) == 1: 
    oOptParse.print_help( ) 
    sys.exit( 1 ) 
aOptions = oOptParse.parse_args( ) 
oOptions =  aOptions[0] 
 
print (oOptions.arg) 

你知道问题出在哪里吗?

非常感谢!

请您参考如下方法:

将 shebang 放在 python 文件的开头:

#!/usr/bin/env python 

通过以下方式使文件可执行:

chmod +x test.py 

然后输入:

./test.py --arg hello 

在Windows系统下,可以在Cygwin下进行上述操作,或者通过以下方式将扩展名.py关联到Python:

C:\> assoc .py=Python.File 
C:\> ftype Python.File=C:\Path\to\python.exe "%1" %*