第一次在这里提问。我想做的是在将 exe 路径分配给变量后使用 os.system 启动可执行文件,并让 os.system 打开分配给变量的路径。如果我只将路径粘贴在括号中(带引号 ofc),它就可以正常工作,但是当我只有变量时,它不会启动任何东西。我已经在同一个变量上尝试了打印功能,它正确地打印了路径。这是我创建变量然后调用的方法。
config = open("config.txt")
lines=config.readlines()
appone = lines[0]
def launchappone():
os.system(appone)
我什至在我的配置文件中的文本上加上了引号,但仍然没有骰子。有什么帮助吗?谢谢。
最佳答案
现在,您应该使用标准库 subprocess
模块来执行此类任务。
此外,您应该始终对文件使用上下文管理器。它们处理自动关闭和异常处理。
还可能出现的问题是,readlines()
将以列表形式返回文件中的所有行,但带有结束行字符。
使用 f.read().splitlines()
删除尾行或在各个行上调用 .strip()
。
把它们放在一起:
import subprocess as sp
with open('config.txt') as config:
lines = config.read().splitlines()
appone = lines[0]
def launch_appone():
sp.run([appone])
编辑:Python 文档还提到不应再使用 os.system
The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.
关于python - 使用 os.system 从分配给变量的路径启动可执行文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43506784/