使用os.system从分配给变量的路径启动可执行文件? [英] Use os.system to launch executable from path assigned to a variable?

查看:313
本文介绍了使用os.system从分配给变量的路径启动可执行文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次在这里提问。我想做的是在将exe路径分配给变量后,使用os.system启动可执行文件,并让os.system打开分配给该变量的路径。如果我仅将路径粘贴在括号中(使用引号ofc),则此方法很好,但是当我仅在其中包含变量时,它不会启动任何内容。我在相同的变量上尝试过打印功能,它可以正确打印出路径。这就是我创建变量然后调用的内容。

first time asking a question here. What I am trying to do is launch an executable with os.system after the exe path has been assigned to a variable, and having os.system open the path assigned to the variable. It works fine if I have just the path pasted in the parenthesis (with the quotes ofc) but when I only have the variable there, it does not launch anything. I have tried the print function on the same variable and it prints the path out correctly. Here is what I have that creates the variable and then the call.

config = open("config.txt")
lines=config.readlines()
appone = lines[0]

def launchappone():
os.system(appone)

我什至将引号放在我拥有的配置文件中,但仍然没有骰子。有什么帮助吗?谢谢。

I have even put the quotes on the text in the config file I have, but still no dice. Any help? Thanks.

推荐答案

现在,您应该使用标准库子进程模块完成这些任务。

Nowadays, you should use the standard libraries subprocess module to do such tasks.

此外,您应该始终对文件使用上下文管理器。它们处理自动关闭和异常处理。

Also, you should always use context managers with files. These handle automical closing and exception handling.

可能还会出现的问题是, readlines()将返回文件中的所有行均作为列表,但带有结束符
使用 f.read()。splitlines()删除结束行或调用 .strip()

What might also be a problem, is that readlines() will return all lines in the file as a list but with endline character. Use f.read().splitlines() to remove the endline or call .strip() on the individual lines.

将其放在一起:

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

also the python docs mention that os.system should not be used anymore


子流程模块提供了更强大的功能产生新流程并获取其结果;使用该模块优于使用此功能。有关一些有用的食谱,请参见子过程文档中的用子过程模块替换较早的功能部分。

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

这篇关于使用os.system从分配给变量的路径启动可执行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆