我有这样的代码:
def hello():
return 'Hi :)'
我如何直接从命令行运行它?
我有这样的代码:
def hello():
return 'Hi :)'
我如何直接从命令行运行它?
当前回答
如果你用pip安装runp包,这是一个运行的问题:
润普 myfile.py 你好
您可以在https://github.com/vascop/runp上找到该存储库
其他回答
有趣的是,如果目标是打印到命令行控制台或执行其他一些minute python操作,你可以像这样将输入管道到python解释器:
echo print("hi:)") | python
以及管道文件..
python < foo.py
*请注意,第二个扩展名不一定是.py。 **还请注意,对于bash,您可能需要转义字符
echo print\(\"hi:\)\"\) | python
从myfile导入hello;hello() `,其中myfile必须替换为Python脚本的基名。(例如,myfile.py变成myfile)。
但是,如果hello()是Python脚本中的“永久”主入口点,那么通常的方法如下:
def hello():
print "Hi :)"
if __name__ == "__main__":
hello()
这允许您通过运行python myfile.py或python -m myfile来执行脚本。
这里解释一下:__name__是一个特殊的Python变量,保存当前正在执行的模块的名称,除非从命令行启动模块,在这种情况下,它会变成"__main__"。
使用python-c工具(pip install python-c),然后简单地写:
$ python-c foo 'hello()'
或者如果你的python文件中没有函数名冲突:
$ python-c 'hello()'
如果你用pip安装runp包,这是一个运行的问题:
润普 myfile.py 你好
您可以在https://github.com/vascop/runp上找到该存储库
我需要在命令行上使用各种python实用程序(range, string等),并为此专门编写了pyfunc工具。你可以用它来丰富你的命令行使用经验:
$ pyfunc -m range -a 1 7 2
1
3
5
$ pyfunc -m string.upper -a test
TEST
$ pyfunc -m string.replace -a 'analyze what' 'what' 'this'
analyze this