简体   繁体   English

使bash从python函数输出一个值(字符串)

[英]making bash output a value(string) from a python function

I have a simple function that simply prints "Hi!".我有一个简单的函数,可以简单地打印“嗨!”。 I want to use bash to call my function, instead of lets say IDLE.我想使用 bash 来调用我的函数,而不是说 IDLE。 However bash doesn't seem to want to print the output returned from the hi(): function.但是 bash 似乎不想打印从 hi(): 函数返回的输出。

    #!/usr/bin/python
    def hi():
        print 'Hi!'

This doesn't print "Hi!", when I type python hi.py (or ./hi.py) into bash当我在 bash 中输入 python hi.py(或 ./hi.py)时,这不会打印“嗨!”

However if I do not include the print statement inside of a function, but just inside the file hi.py as a lone print 'Hi!'但是,如果我不在函数中包含打印语句,而是在文件 hi.py 中作为单独的打印“嗨!” statement;陈述; then bash does output text "Hi!"然后 bash 确实输出文本“嗨!” accordingly.因此。 From bash this code below outputs Hi!从 bash 下面的代码输出嗨!

    #!/usr/bin/python
    print 'Hi!'

From within bash, how might I make bash output the string from the function hi(): in the file hi.py?在 bash 中,我如何让 bash 输出来自函数 hi(): 在文件 hi.py 中的字符串?

Thanks谢谢

You need to do this in you hi.py:您需要在 hi.py 中执行此操作:

  def hi():
      print 'Hi!'

  if __name__ == '__main__':
      hi()

Then it will work in bash:然后它将在 bash 中工作:

#!/bin/bash
python hi.py

Are you calling the function in your python script?你是在你的 python 脚本中调用函数吗? In order to get the print statement in your function to be activated you actually need to call the function.为了激活函数中的打印语句,您实际上需要调用该函数。 For example running python test.py for this file prints "Hi!"例如,为此文件运行python test.py打印“嗨!”

# Program named test.py
def output():
    print('Hi!')

output() # Calling the output function which will cause a print statement

Also calling this python file in bash works also.在 bash 中调用这个 python 文件也有效。 For example calling bash call.sh for this script worked and printed "Hi!"例如,为此脚本调用bash call.sh工作并打印“嗨!” to the command line到命令行

#!/bin/bash
# Script to call python file
python test.py

Assuming that you want to execute a particular function.The python executable accepts the '-c' flag to indicate that you are passing it code.假设你想执行一个特定的函数。python 可执行文件接受 '-c' 标志来表明你正在传递它的代码。 So if my file (hi.py) is:所以如果我的文件(hi.py)是:

def hi():
        print 'Hi!'

Then I could do:然后我可以这样做:

$ python -c "execfile('hi.py'); hi()"

which pints the output输出

HI!

Reason原因

when you execute a python script you should tell it where to start.Since Hi is not a main function you need to manually call hi()当你执行一个 python 脚本时,你应该告诉它从哪里开始。因为Hi不是一个主函数,你需要手动调用hi()

def hi():
        print 'Hi!'
hi()

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

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