【问题标题】:python pass variable through os.system [duplicate]python通过os.system传递变量[重复]
【发布时间】:2017-12-29 14:41:07
【问题描述】:

这会在我的目录中获取最新的 mp3 文件

new_file = [(os.path.getmtime(ft) , os.path.basename(ft))
            for ft in os.listdir(path) if ft.lower().endswith('.mp3')]

new_file.sort()

将最新的文件分配给我要播放的文件

playFile = new_file[0][1]

获取文件的目录。

PlayfileDir = os.getcwd() + '\\' + str(playFile)

播放文件。这是我得到错误“PlayfileDir”找不到的地方。

os.system('start "PlayfileDir"')

【问题讨论】:

  • 不要使用os.system;使用subprocess 模块。
  • 省点麻烦,使用subprocess.run()。
  • 您的文件路径错误。该文件位于path,而不是os.getcwd()。
  • 但是这里有很多问题。在所有其他调用中,使用字符串连接构建命令。你为什么不在最后一个也这样做?
  • 你不是说os.system('start \'{}\''.format(PlayfileDir))吗?顺便说一句 - 请 - 不要使用骆驼套,蛇套ftw!

标签: python


【解决方案1】:

由于PlayfileDir 是string 的变量,您可以将其连接到'start'(正如@cdarke 所指出的,您还需要添加引号!)。正如您目前所拥有的那样,您正在尝试启动实际的字符串'PlayfileDir',而不是变量中的字符串。

所以,你应该这样做:

os.system('start "' + PlayfileDir + '"')

【讨论】:

  • 请注意,PlayfileDir 变量已经有一个字符串。不需要演员。
  • @Code-Apprentice 是的
  • @cdarke 谢谢!我在 Linux 上,所以无法对此进行测试,但绝对是关键!
  • @JoeIddon: 也适用于 Linux,尽管没有人在他们正常的头脑中会有一个包含空格的目录名称 :-)
【解决方案2】:

这是开始使用pathlib的绝佳机会!

from pathlib import Path

p = input("Gimme a path: ")

newest_mp3 = sorted(Path(p).glob('*.mp3'), reverse=True, key=lambda p: p.stat().st_mtime)[0]

os.system('start "{}"'.format(newest_mp3))

【讨论】:

  • 嗨,这很好用,但它会打开一个命令窗口,我必须在其中输入文件名才能播放它。有没有办法自动做到这一点
  • 不要执行os.system(...),而是执行print(...) 并查看生成的内容。
猜你喜欢
  • 2014-04-01
  • 2020-07-14
  • 2017-03-27
  • 1970-01-01
  • 2021-07-08
  • 2020-11-08
  • 1970-01-01
  • 2018-11-05
  • 2021-11-20
相关资源
最近更新 更多