我有这样的代码:

def hello():
    return 'Hi :)'

我如何直接从命令行运行它?


当前回答

让您的生活更轻松,安装Spyder。打开文件,然后运行它(单击绿色箭头)。之后,您的hello()方法被定义并被IPython控制台所知道,因此您可以从控制台调用它。

其他回答

使用-c(命令)参数(假设你的文件名为foo.py):

$ python -c 'import foo; print foo.hello()'

或者,如果你不关心命名空间污染:

$ python -c 'from foo import *; print hello()'

中间立场是:

$ python -c 'from foo import hello; print hello()'

只要把hello()放在函数下面的某个地方,它就会在你执行python your_file.py时执行

为了一个更简洁的解决方案,你可以使用这个:

if __name__ == '__main__':
    hello()

这样,函数只会在运行文件时执行,而不会在导入文件时执行。

下面是Odd_Even_function.py文件,其中包含函数的定义。

def OE(n):
    for a in range(n):
        if a % 2 == 0:
            print(a)
        else:
            print(a, "ODD")

现在从命令提示符下面调用相同的选项为我工作。

选项1 exe\python.exe -c的完整路径 “进口Odd_Even_function;Odd_Even_function.OE(100)“

选项2 exe\python.exe -c的完整路径 from Odd_Even_function import OE;OE(100)“

谢谢。

如果你用pip安装runp包,这是一个运行的问题:

润普 myfile.py 你好

您可以在https://github.com/vascop/runp上找到该存储库

就像这样: call_from_terminal.py

# call_from_terminal.py
# Ex to run from terminal
# ip='"hi"'
# python -c "import call_from_terminal as cft; cft.test_term_fun(${ip})"
# or
# fun_name='call_from_terminal'
# python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
def test_term_fun(ip):
    print ip

这在bash中工作。

$ ip='"hi"' ; fun_name='call_from_terminal' 
$ python -c "import ${fun_name} as cft; cft.test_term_fun(${ip})"
hi