如何在 Python 可执行文件中传递输入值?

huangapple go评论127阅读模式
英文:

How to pass input values in python executable file?

问题

有时,在命令提示符中调用.exe文件时,我们还会在一个命令中传递一些参数或属性,这些参数通常以下划线“--”或仅以下划线。例如,app.exe parametersapp.exe --parameter="value"。我们如何在Python中创建这种类型的.exe文件。

为此,我创建了一个名为“file.py”的Python文件,其中包含以下代码:

variable = input()
print("You have entered " + variable)

将其导出为“file.exe”后,我尝试调用它:file.exe "any_text",但它不起作用。但是,如果我尝试调用它:file.exe --variable="any_text",仍然不起作用。
请告诉我如何创建这种类型的.exe文件。提前感谢。

英文:

Some times, when we call an .exe file in command prompt, we also pass some parameters or attributes in one command. which are mostly following hyphen "--" or simply following a space. For example, app.exe parameters or app.exe --parameter="value". How we can create such type type of exe files in python.

For this I created a python file "file.py" which has following code :

variable = input()
print("You have entered "+variable)

After exporting it into "file.exe" I tried to call it as :file.exe "any_text But it doesn't work but I try to call it as :file.exe --variable="any_text". but still not worked.
Let me know how to create such type of .exe files. Thanks in advance.

答案1

得分: 2

在Python中创建一个可接受命令行参数的可执行文件时,最好使用argparse模块。

示例:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--variable', help='Input variable')

args = parser.parse_args()

print("You have entered " + args.variable)

然后,当运行脚本时,您可以传递"--variable"参数的,例如:

file.exe --variable any_text
英文:

When creating an executable file in Python that which accepts command-line arguments, better to use the argparse module.

Example:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--variable', help='Input variable')

args = parser.parse_args()

print("You have entered " + args.variable)

Then, when run the script, you can pass in the value of the "--variable" argument such as:

file.exe --variable any_text

huangapple
  • 本文由 发表于 2023年3月12日 16:14:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75711831.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定