简体   繁体   English

如何通过Python文件在控制台中运行功能?

[英]How to run function in console through Python file?

I have created this function in a Python file: 我已经在Python文件中创建了此函数:

def abc (xyz):
    return xyz

I saved the file in /var/www/ with the file name a.py . 我将文件保存在/var/www/ ,文件名为a.py

Now I want to run this function in an Ubuntu console and pass a parameter to this function. 现在,我想在Ubuntu控制台中运行此功能,并将参数传递给该功能。 How can I do this? 我怎样才能做到这一点? I have tried this: 我已经试过了:

jaskaran@jaskaran-Vostro-1550:/var/www$ python3 a.py

This does not show me any error. 这不会显示任何错误。 How can I call the function and be able to see the output in the console? 如何调用该函数并能够在控制台中看到输出?

The script is running, it just that it only defines the function, it does not execute it. 该脚本正在运行,只是它只定义了功能,而不执行它。 You need to invoke the function from within your Python script. 您需要在Python脚本中调用该函数。 Typically this is done like this: 通常,这样做是这样的:

def abc(xyz):
    print(xyz)

if __name__ == "__main__":
    abc(123)

You can pass command line arguments to abc() like this: 您可以像这样将命令行参数传递给abc()

import sys

def abc(xyz):
    print(xyz)

if __name__ == "__main__":
    abc(sys.argv[1])

Then you can run it from your shell command line: 然后,您可以从shell命令行运行它:

$ python script.py 123546
123456

As you can see, the command line argument "123456" was passed to abc() from the sys.argv list which represents the arguments passed to the script (sys.argv[0] is the script name). 如您所见,命令行参数“ 123456”已从sys.argv列表传递给abc() ,该列表表示传递给脚本的参数(sys.argv [0]是脚本名称)。

first thing if you want to run the method abc 如果要运行abc方法,则第一件事

you need to know many things main() the excution of program starts from main() in python 您需要了解很多事情main()程序的执行从python中的main()开始

 def abc(xyz):
       return xyz
 if __name__ == "__main__":
      abc("sundar")

to pass arguments like below you need to use sys.argv 传递类似下面的参数,您需要使用sys.argv

$python a.py "sundar"

import sys
def abc(xyz):
    return xyz
if __name__ == "__main__":
    print abc(sys.argv[1])

#output sundar

The Python sys module provides access to any command-line arguments via the sys.argv . Python sys模块可通过sys.argv提供对任何命令行参数的访问。 sys.argv is the list of command-line arguments and Here sys.argv[0] is the program ie. sys.argv是命令行参数的列表,此处sys.argv[0]是程序,即。 script name. 脚本名称。

Try using something like this: 尝试使用如下所示的内容:

def abc(xyz):
    print(xyz)

if __name__ == "__main__":
    abc(input("Enter something: "))

This will print in the console what you enter as input! 这将在控制台中打印您输入的内容! ;) ;)

i hope this helps 我希望这有帮助

$ python     
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> from a import abc
>>> abc(123)
123
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM