我是一个python新手,我在使用位于Open explorer on a file的一些非常有用的代码制作模块时遇到了一些困难。
我无法弄清楚我做错了什么。
我收到以下错误消息:
第31行:C:\ Apps \ E_drive \ Python_win32Clipboard.pdf第34行:r'explorer / select,“C:\ Apps \ E_drive \ Python_win32Clipboard.pdf”'Traceback(大多数) 最近的呼叫最后):文件 “P:\ DATA \ VB \ Python_MarcsPrgs \ Python_ItWorks \ Open_Win_Explorer_and_Select_File.py” 第42行,在 Open_Win_Explorer_and_Select_Fil(filepath)文件“P:\ Data \ VB \ Python_MarcsPrgs \ Python_ItWorks \ Open_Win_Explorer_and_Select_File.py”, 第35行,在Open_Win_Explorer_and_Select_Fil中 subprocess.Popen(Popen_arg)文件“C:\ Python27 \ lib \ subprocess.py”,第679行, init errread,errwrite)_execute_child中的文件“C:\ Python27 \ lib \ subprocess.py”,第893行 startupinfo)WindowsError:[错误2]系统找不到指定的文件
这是我的模块:
"""
Open Win Explorer and Select File
# "C:\Apps\E_drive\Python_win32Clipboard.pdf"
"""
import sys
import os, subprocess, pdb
def fn_get_txt_sysarg():
"Harvest a single (the only) command line argument"
# pdb.set_trace()
try:
arg_from_cmdline = sys.argv[1]
arg_from_cmdline = str(arg_from_cmdline)
except:
this_scriptz_FULLName = sys.argv[0]
ErrorMsg = "Message from fn_get_txt_sysarg() in Script (" + this_scriptz_FULLName + '):\n' \
+ "\tThe Script did not receive a command line argument (arg_from_cmdline)"
returnval = arg_from_cmdline
return returnval
def Open_Win_Explorer_and_Select_Fil(filepathe):
# harvested from... https://stackoverflow.com/questions/281888/open-explorer-on-a-file
#import subprocess
#subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')
f = str(filepathe)
print "line 31: " + f
Popen_arg = "r'explorer /select, " + '"' + f + '"' + "'"
Popen_arg = str(Popen_arg)
print "line 34: " + Popen_arg
subprocess.Popen(Popen_arg)
if __name__ == '__main__':
filepath = fn_get_txt_sysarg()
Open_Win_Explorer_and_Select_Fil(filepath)
非常感谢任何帮助。
Marceepoo
答案 0 :(得分:6)
我认为问题在于Popen_arg
的初始化。请注意输出中Popen_arg
的值为:
r'explorer /select, "C:\Apps\E_drive\Python_win32Clipboard.pdf"'
这实际上是一个python raw string literal。您希望Popen_arg具有此字符串文字所代表的值,而不是此字符串文字本身。我想如果你把它改成
Popen_arg = r'explorer /select, "' + f + '"'
它会更好用。还要注意该行:
Popen_arg = str(Popen_arg)
无效,可以安全删除。
答案 1 :(得分:3)
我复制了你的代码并在我的机器上运行它,发现了两个错误。 answer srgerg provided解决了其中一个错误。另一种是,当命令行中没有指定参数时,Python会在fn_get_txt_sysarg()中触发错误。下面是一些示例代码,修复了错误以及其他一些清理:
"""
Open Win Explorer and Select File
"""
import sys
import subprocess
def fn_get_txt_sysarg():
"""Harvest a single (the only expected) command line argument"""
try:
return sys.argv[1] # str() would be redundant here
except:
ErrorMsg = 'Message from fn_get_txt_sysarg() in Script (' + sys.argv[0] + '):\n' + '\tThe Script did not receive a command line argument'
sys.exit(ErrorMsg)
def Open_Win_Explorer_and_Select_Fil(filepath):
# harvested from: https://stackoverflow.com/questions/281888/open-explorer-on-a-file
Popen_arg = 'explorer /select,"' + filepath + "'" # str() is redundant here also
subprocess.Popen(Popen_arg)
if __name__ == '__main__':
filepath = fn_get_txt_sysarg()
Open_Win_Explorer_and_Select_Fil(filepath)