[英]Python - Run function with parameters in command line
是否可以在命令行中運行帶有參數的python腳本,如下所示:
./hello(var=True)
還是必須這樣做:
python -c "from hello import *;hello(var=True)"
第一種方法是更短和更簡單。
大多數外殼將括號用於分組或子外殼。 因此,您無法從普通外殼調用任何命令,例如command(arg)
...,但是您可以編寫帶有參數的python腳本(./hello.py)。
import optparse
parser = optparse.OptionParser()
parser.add_option('-f', dest="f", action="store_true", default=False)
options, remainder = parser.parse_args()
print ("Flag={}".format(options.f))
然后用python hello.py -f
調用它
./hello(var=True)
在REPL shell中是不可能的。 在某些情況下,在當前的shell會話中提供python函數可能會很有用。 這是一個使您的python函數在您的shell環境中可用的解決方法。
# python-tools.sh
#!/usr/bin/env bash
set -a # make all available export all variable)
function hello(){
cd "/app/python/commands"
python "test.py" $@
}
python腳本的內容
#! /usr/bin/env python
# /app/python/commands/test.py script
import sys
def test(*args):
print(args)
if __name__ == '__main__':
if sys.argv[1] in globals().keys():
print(sys.argv[1])
globals()[sys.argv[1]](sys.argv[2:])
else:
print("%s Not known function" % sys.argv[1])
然后獲取python-tools.sh
source python-tools.sh
hello功能可用后
$ hello test arg2 arg2
test
(['arg2', 'arg2'],)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.