我正在尝试完成自动化无聊的工作-“在Windows上运行Python程序”中的附录B,但是当我WIN-R脚本和argv时,出现错误“找不到'__ main __'模块” C:\路径。
我已经创建了.py脚本以及批处理文件,更改了系统变量路径,但仍然无法使程序从WIN-R运行。
我的pw.py脚本如下:
#! /usr/bin/env python3
# pw.py - An insecure password locker program.
PASSWORDS = {'email': 'F7min1BDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
import sys
import pyperclip
if len(sys.argv) < 2:
print('Usage: python pw.py [account] - copy account password')
sys.exit()
account = sys.argv[1] #first command line arg is the account name
if account in PASSWORDS:
pyperclip.copy(PASSWORDS[account])
print('Password for ' + account + ' copied to clipboard.')
else:
print('There is no account named ' + account)
我的pw.bat文件如下:
@py.exe C:\Users\lukev\PythonScripts %*
@pause
当我在WIN-R中运行pw email
时,出现以下错误:
C:\Users\lukev\AppData\Local\Programs\Python\Python38-32\python.exe: can't find '__main__' module in 'C:\\Users\\lukev\\PythonScripts'
从我的研究中,我发现shebang行不应该如书中所述,而应为#! /usr/bin/env python3
,另一种可能是如果我安装了多个版本的Python但没有其他版本安装,仍然有问题。
以下是python文件,批处理文件,系统环境变量和错误消息的屏幕截图:
答案 0 :(得分:0)
您使用
批处理文件中的@py.exe C:\Users\lukev\PythonScripts %*
。传递到py.exe
的路径是文件夹路径。
这会产生错误:
C:\Users\lukev\AppData\Local\Programs\Python\Python38-32\python.exe: can't find '__main__' module in 'C:\\Users\\lukev\\PythonScripts'
错误是精确的。该路径是文件夹路径,因此Python要做的是寻找入口点。如图所示,该入口点是__main__.py
。如果找不到入口点,则会显示错误消息。
如果要执行文件,请直接执行:
@py.exe C:\Users\lukev\PythonScripts\pw.py %*
要了解__main__
模块的入口点,请创建一个名为C:\PythonExecutable
的文件夹,并在名为__main__.py
的目录内创建一个文件。在此文件中插入以下代码:
import sys
if __name__ == '__main__':
# Check command line arguments.
if len(sys.argv) > 1:
if sys.argv[1] == '-h':
print('I am here to help')
else:
for index, item in enumerate(sys.argv):
print(index, item)
else:
print('I am ', __name__)
在命令提示符中输入一些命令:
C:\> py PythonExecutable I am __main__ C:\> py PythonExecutable -h I am here to help C:\> py PythonExecutable arg1 arg2 arg3 "I am the fourth" 0 PythonExecutable 1 arg1 2 arg2 3 arg3 4 I am the fourth C:\>
__main__.py
中的shebang行未应用,因为py.exe
不会从该文件中读取。