[英]what are the guidelines for the key in the max function & is that key related to the dictionary keys in Python ? ex: max(arg1, arg2, *args[, key])
[英]How do I properly use the “--args” option when running “$ open myscript.py --args arg1 arg2” on command line
我已經有一段時間來到stackoverflow了,我非常感謝這種不可思議的資源,因為它在無數次場合都為我提供了幫助,但這是我的第一個問題,所以請對我保持憐憫;)
當我使用“ open”命令從命令行運行python腳本時,我試圖將命令行選項傳遞給我的python腳本。 我知道我可以簡單地使用$ python myscript.py [arg1] [arg2],但實際上,我盡可能地嘗試使用“ open”命令。
這是我的python腳本(myscript.py):
#!/usr/local/bin/python
import optparse
import sys
def main():
parser = optparse.OptionParser()
parser.add_option('--arg1', action="store", dest="arg1", type="int", default="0")
parser.add_option('--arg2', action="store", dest="arg2", type="int", default="0")
opts, remainder = parser.parse_args()
print "Options: ", str(opts)
print "Remainders: ", str(remainder)
print "Argv: ", sys.argv[:]
if __name__ == "__main__":
main()
這是我在終端中運行的命令:
$ open -a terminal myscript.py --args --arg1=5 --arg2=10
並從中輸出:
Options: {'arg1': 0, 'arg2': 0}
Remainders: []
Argv: ['/Users/test/Desktop/myscript.py']
因此腳本正在運行,但是沒有傳遞“ --args”,腳本僅使用默認值作為參數! 這是打開命令的--args選項的文檔:
--args All remaining arguments are passed in argv to the application's main() function instead of opened.
我嘗試了各種嘗試來使它起作用,但是我無法通過“打開”將參數輸入到腳本中。 在此先感謝您提供任何有關如何使其正常工作的指導或建議。
您的語法很好; open
會將多余的參數傳遞給Terminal
,但是Terminal忽略了它們。 例如,這只是打開一個外殼,而不做任何回顯:
open -a terminal /bin/bash --args -c 'echo foo bar'
如果要在新的“終端”窗口中運行帶有參數的命令,則需要執行其他操作。 查看此問題的答案以獲取想法。
盡管我仍然不清楚如何在打開命令中正確使用--args選項,但是我找到了合適的解決方法。
echo python /Users/test/Desktop/myscript.py --arg1=5 --arg2=10 > myscript.command; chmod +x myscript.command; open myscript.command
並從中輸出:
Options: {'arg1': 5, 'arg2': 10}
Remainders: []
Argv: ['/Users/test/Desktop/opt.py', '--arg1=5', '--arg2=10']
我最初想要使用open命令的主要原因是要打開一個新的終端窗口以運行帶參數的myscript。 解決方法是做同樣的事情,但是只是創建一個終端shell腳本,使其成為UNIX可執行文件,並在不帶--args的情況下使用“ open”與python一起運行。 我仍然想了解如何在打開時使用--args,以及為什么不能在不動態創建其他shell腳本的情況下做到這一點,但我很高興它能解決問題;)非常感謝Mark Reed為我指出正確的方向! 我希望這也有幫助其他人的一天。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.