简体   繁体   English

将os.system()的输出存储在变量中

[英]Storing output of os.system() in a variable

I am generating a random word for my Hangman game, and hence want to generate a random word. 我正在为Hangman游戏制作一个随机词,因此想生成一个随机词。

I am using the /usr/share/dict/words file and doing the following: 我正在使用/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

But when I check the value of word, it has the value 0 (Which is most probably the exit status of the command in round brackets). 但是当我检查word的值时,它的值为0(这很可能是该命令在圆括号中的退出状态)。 How do I store the word in my variable? 如何将单词存储在变量中?

Don't call shell commands from Python. 不要从Python调用shell命令。 You can do everything in Python that shell commands can. 您可以使用Shell命令执行的所有Python操作。 It's better to implement this either in pure Python or in pure Bash. 最好以纯Python或纯Bash来实现。

A simple implementation of your task is to read the entire contents of /usr/share/dict/words into a list, and then use the random module to select an item randomly. 您的任务的简单实现是将/usr/share/dict/words的全部内容读入列表,然后使用random模块random选择一个项目。 The advantage of this solution is that it scans the file contents only once. 该解决方案的优点是它仅扫描文件内容一次。 Its drawback is reading the contents in memory. 它的缺点是读取内存中的内容。 (Since that's less than 1MB, that should be a negligible concern on a modern system.) (由于小于1MB,因此在现代系统上应该忽略不计。)

If you want to do this in Python, use the subprocess module instead. 如果要在Python中执行此操作,请改用subprocess模块。

Something like: 就像是:

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'

Official docs here . 官方文档在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM