![](/img/trans.png)
[英]“command not found” using line in argument to os.system using python
[英]Creating a Command Line Argument System for Embedded Python
我有一个主要的python3文件如下:
import additionalfunctions
userIn = input("Select Function and command line arguments: ")
“附加功能.py”如下:
def arbitraryfunction(arg):
print("you entered the value: " + str(arg))
我面临的问题是我需要在主 python 文件中使用“input()”来选择这个函数,并将一个参数传递给它。 有谁知道如何解析变量 'userIn' 以选择和运行一个函数,并将参数传递给它?
您能提供的任何帮助将不胜感激!
您可以使用默认包argparse
并创建一个如下所示的函数。
代码:
import argparse
#>>>>>>>>>>>>>>>>>>>>>>> ARGUMENT PARSING <<<<<<<<<<<<<<<<<<<<<<<<<<<<
def args():
parser = argparse.ArgumentParser()
parser.add_argument('-A','--Arg1',type=int,help='I am Argument 1',required=False)
parser.add_argument('-B','--Arg2',type=str,help='I am Argument 2',required=True)
parser.add_argument('-C','--Arg3',type=str,help='I am Argument 3',required=True)
args = parser.parse_args()
print("PARSING ARGUMENTS COMPLETED")
argparse 文档: https : //docs.python.org/3/library/argparse.html
除了完全正确的 High-Octane 答案之外,一旦您有了命令行参数,您就可以使用exec()
运行选定的函数并将参数传递给它。 根据您自己的代码尝试此操作:
def arbitraryfunction(arg):
print("you entered the value: " + str(arg))
allowed_functions = ['arbitraryfunction']
# write "arbitraryfunction 0" or similar when asked
userIn = input("Select Function and command line arguments: ")
args = userIn.split(" ")
if len(args) >= 2:
fun = args[0]
arg = args[1]
if fun in allowed_functions:
exec(fun + "(" + str(arg) + ")")
else:
print("Function not found. Please try again")
然后,您必须像这样导入附加功能(为了简单起见,我将其包含在同一个脚本中):
from additionalfunctions import *
免责声明:这不应在任何生产敏感环境中使用,因为它可以执行恶意脚本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.