简体   繁体   中英

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.

I am using the /usr/share/dict/words file and doing the following:

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). How do I store the word in my variable?

Don't call shell commands from Python. You can do everything in Python that shell commands can. It's better to implement this either in pure Python or in pure 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. 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.)

If you want to do this in Python, use the subprocess module instead.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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