簡體   English   中英

將os.system()的輸出存儲在變量中

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

我正在為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(這很可能是該命令在圓括號中的退出狀態)。 如何將單詞存儲在變量中?

不要從Python調用shell命令。 您可以使用Shell命令執行的所有Python操作。 最好以純Python或純Bash來實現。

您的任務的簡單實現是將/usr/share/dict/words的全部內容讀入列表,然后使用random模塊random選擇一個項目。 該解決方案的優點是它僅掃描文件內容一次。 它的缺點是讀取內存中的內容。 (由於小於1MB,因此在現代系統上應該忽略不計。)

如果要在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'

官方文檔在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM