如何从 shell 运行 .py 文件内的 python 定义?

emp*_*les 4 python command-line

我的函数位于与该函数同名的 .py 文件内:

\n\n
emp@emp:~$ python ~/Dropbox/emp/Python/stromkosten_pro_jahr.pyempedokles@empedokles:~$ stromkosten_pro_jahr(20,3)\nbash: Syntaxfehler beim unerwarteten Wort \xc2\xbb20,3\xc2\xab\nemp@emp:~$ \n
Run Code Online (Sandbox Code Playgroud)\n\n

错误在哪里?

\n

Adi*_*tya 5

您需要cd进入 python 文件所在的目录,然后调用 python 交互式 shell 才能以交互方式调用和运行函数。

# cd to the directory
$ cd ~/Dropbox/emp/Python/

# invoke the python interactive shell
$ python     # use `python3` to invoke the Python3 shell
Run Code Online (Sandbox Code Playgroud)

Python 交互式 shell 看起来像:

Python 2.7.6 (default, Mar 22 2014, 22:59:38) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
Run Code Online (Sandbox Code Playgroud)

在这里,您可以导入模块(您的 *.py 文件)并运行其中编写的函数:

>>> from stromkosten_pro_jahr import stromkosten_pro_jahr
>>> stromkosten_pro_jahr(20,3)
[The output of function would be shown right here]
Run Code Online (Sandbox Code Playgroud)

有关更多信息,我建议阅读Python 教程