python - 使用 os.system 从分配给变量的路径启动可执行文件?

标签 python python-3.x config os.system

第一次在这里提问。我想做的是在将 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.

https://docs.python.org/3/library/os.html#os.system

关于python - 使用 os.system 从分配给变量的路径启动可执行文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43506784/

相关文章:

python - 如果列检查为特定值,则提取行 - Unix

python - Python3 字典的问题

ruby-on-rails - 使用 heroku 和 sidekiq 时,我将 ENV ["WEB_CONCURRENCY"] 设置为什么

node.js - VSCode上的pwa-node类型启动配置是什么?

python - 无法更改 Raspberry pi 上 PyAudio 中的卡索引

python - Django formset - 如何为 modelformset 中的每个表单提供不同的查询集

android - beeware 将 toga imageview 添加到 android

python - 问题 和 列出和分隔字符

c# - 在配置文件中使用引号作为值

python - 用python选择大于内存数据分析的框架