我目前正在使用一个包含以下代码的 python 脚本。它打开一个包含 JSON 文本的文件并从中确定一个值。
browseFiles()
def browseFiles():
global fileName
fileName = filedialog.askopenfilename(title = "Select a File", filetypes = (("All Files","*.*")))
# Open the File in Read Mode
fileFile = open(fileName, "r")
# Read the file
fileContent = fileFile.read()
# Render the JSON
fileJSON = json.loads(fileContent)
# Determine the ID
myID = fileJSON["key"]
# Update the Status
windowRoot.title(myID)
... remaining code
fileFile.close()
但是,每次都打开该程序然后导航到它不太方便。
Windows 在文件资源管理器中具有“打开方式”功能,我们可以右键单击文件并使用 Word 等应用程序打开它。
如何在Python脚本中实现这个?我是否应该考虑首先创建此脚本的 .exe,如果是,那么哪个库最适合这个? (考虑到它是一个非常小且简单的实用程序)
一些可能不需要的额外信息:我正在使用 Tkinter 作为 GUI。
(顺便说一句,如果这个问题已经存在于 StackOverFlow 或任何其他网站上,那么请评论该链接,而不是仅仅将其标记为重复。我尝试了很多搜索,但找不到任何内容)
问候,
维万。
简单的例子:
import sys
try:
#if "open with" has been used
print(sys.argv[1])
except:
#do nothing
pass
用法示例:
import sys
from tkinter import filedialog
filetypes = (('Text files', '*.txt'),('All files', '*.*'))
#if filename is not specified, ask for a file
def openfile(filename = ''):
#print contents of file
if filename == '':
filename = filedialog.askopenfilename(title='Open A File',filetypes=filetypes)
with open(filename,'r', encoding="utf-8") as file:
read = file.read()
print(read)
try:
#if "open with" has been used
openfile(filename = sys.argv[1])
except:
#ask for a file
openfile()
然后用 nuitka (或任何你使用的工具)将其编译为 exe,
并尝试一下。
或者(用于测试,无需每次进行更改时都进行编译):
制作一个 .bat 文件
@echo off
py program.py %*
pause
然后每次你想运行它时,
you open with
that file.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)