之前已经用Python代码实现了检测出win平台中的脚本文件名:
<—————————————————————————- # got python script self file name # extract out file name from command line input: # (1) win # extract xxx from D:\yyy\zzz\xxx.py # (2) Mac # extract xxx from /Users/crifan/dev/yyy/xxx.py def extractFilename(inputStr) : argv0List = inputStr.split(“\\”) scriptName = argv0List[len(argv0List) – 1] # get script file name self possibleSuf = scriptName[-3:] if possibleSuf == “.py”: scriptName = scriptName[0:-3] # remove “.py” return scriptName |
但是现在换成了mac平台,就不起效果了。
所以要去优化。
同时,之前代码中,好像碰巧支持了:
BlogsToWordpress.exe
的情况下,也能提取到文件名:
BlogsToWordpress
另外又想到了,当Mac中用:
python BlogsToWordpress.py
时,之前的
sys.argv[0]
就是python
而不是我们要的文件名了。
python get script file name
Get the name of current script with Python – Stack Overflow
里面提到了:
对于:python foo.py
sys.argv[0]也可以得到foo.py
试试
os.path.basename(__file__)
效果不错:
当前文件是:AutoOrder.py
输出的是:AutoOrder.py
但是如果,想要让我的crifanLib.py中去获得:
调用者,别的文件的文件名,则不行。
试试:
currentFilename = crifanLib.getCurrentFilename() print “currentFilename=%s”%(currentFilename) |
果然可以:
期间,先去解决:
【已解决】Python中如何获得Windows文件完整路径中的文件名
【总结】
用如下代码:
def getBasename(fullFilename): “”” get base filename Examples: xxx.exe -> xxx.exe xxx -> xxx Mac/Linux: your/path/xxx.py -> xxx.py Windows: your\path\\xxx.py -> xxx.py “”” return os.path.basename(fullFilename) def removeSuffix(fileBasename): “”” remove file suffix Examples: xxx.exe -> xxx xxx -> xxx “”” splitedTextArr = os.path.splitext(fileBasename) filenameRemovedSuffix = splitedTextArr[0] return filenameRemovedSuffix def getInputFilename(): “”” get input filename, from argv Examples: python AutoOrder.py -> AutoOrder.py python AutoOrder/AutoOrder.py -> AutoOrder/AutoOrder.py “”” argvList = sys.argv # print “argvList=%s”%(argvList) return argvList[0] def getInputFileBasename(inputFilename = None): “”” get input file’s base name Examples: AutoOrder/AutoOrder.py -> AutoOrder.py “”” curInputFilename = getInputFilename() if inputFilename : curInputFilename = inputFilename # print “curInputFilename=%s”%(curInputFilename) inputBasename = getBasename(curInputFilename) # print “inputBasename=%s”%(inputBasename) return inputBasename def getInputFileBasenameNoSuffix(): “”” get input file base name without suffix Examples: AutoOrder.py -> AutoOrder AutoOrder/AutoOrder.py -> AutoOrder “”” inputFileBasename = getInputFileBasename() basenameRemovedSuffix = removeSuffix(inputFileBasename) return basenameRemovedSuffix |
就可以获取当前脚本文件名了:
更多Python中的file相关的函数可参考:
或:
https://github.com/crifan/crifanLib/blob/master/python/crifanLib.py
或:
https://github.com/crifan/crifanLib/blob/master/python/crifanLib/crifanFile.py
转载请注明:在路上 » 【已解决】Python中如何获取脚本文件名