【问题标题】:Storing output of os.system() in a variable将 os.system() 的输出存储在变量中
【发布时间】:2017-12-17 19:35:23
【问题描述】:

我正在为我的 Hangman 游戏生成一个随机词,因此想要生成一个随机词。

我正在使用/usr/share/dict/words 文件并执行以下操作:

def word_select():
    import os
    word = os.system('head -$((${RANDOM} % `wc -l < /usr/share/dict/words` + 1)) /usr/share/dict/words | tail -1')
    return word

但是当我检查 word 的值时,它的值为 0(这很可能是圆括号中命令的退出状态)。如何将单词存储在变量中?

【问题讨论】:

标签: linux python


【解决方案1】:

不要从 Python 调用 shell 命令。 你可以在 Python 中做 shell 命令可以做的所有事情。 最好在纯 Python 或纯 Bash 中实现这一点。

您的任务的一个简单实现是将/usr/share/dict/words 的全部内容读入一个列表,然后使用random 模块随机选择一个项目。 此解决方案的优点是它只扫描文件内容一次。它的缺点是读取内存中的内容。 (由于小于 1MB,这对于现代系统来说应该是一个可以忽略不计的问题。)

【讨论】:

  • 非常感谢!
【解决方案2】:

如果您想在 Python 中执行此操作,请改用 subprocess 模块。

类似:

Python 3.5.3 (default, Jan 19 2017, 14:11:04) 
[GCC 6.3.0 20170118] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> myVariable = subprocess.check_output(["uptime"])
>>> myVariable
b' 20:48:53 up 42 min,  1 user,  load average: 0,21, 0,26, 0,26\n'

官方文档here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 2018-07-16
    • 1970-01-01
    • 2014-07-02
    • 2015-05-03
    • 1970-01-01
    相关资源
    最近更新 更多