英文:
How to execute python function in vsc terminal
问题
def add(a,b):
return a+b
我在VSC中创建了一个Python函数,我想在终端中执行它,像这样:
add(2,3)
但是这样会出现一个错误,类似于bash: 附近的语法错误 2,3
。
我认为问题出在终端的路径,但我不知道该怎么做。
我尝试了一些与终端路径相关的操作,但我不知道问题出在哪里。
英文:
def add(a,b):
return a+b
I made python function at vsc and I want to execute that function in terminal like
add(2,3)
But if so there is an error like bash: syntax error near unexpected token `2,3'
I think the matter of path of terminal but I do not know what to do
I have tried something related to path of terminal but IDK what is matter
答案1
得分: 1
You need to save the file with the function, then run the function through the command line using python3 -c
.
I created a file sample.py with your function:
def add(a,b):
return a+b
and I ran the following command from the command-line terminal:
python3 -c 'from sample import add; print(add(2,3))';
and the output was:
5
Note that, I am using Linux, that's why it is python3
, for Windows, you need to use python
only.
英文:
You need to save the file with the function, then run the function through the command line using python3 -c
I created a file sample.py with your function
def add(a,b):
return a+b
and I ran the following command from the command-line terminal.
python3 -c 'from sample import add; print(add(2,3))'
and the output was
5
Note that, I am using Linux, that's why it is python3
, for windows, you need to use python
only.
答案2
得分: 1
如果你想经常从命令行运行你的函数,可能最清晰的方式是将它制作成一个可执行脚本。在Linux上:
#!/usr/bin/python3
from sys import argv
def add(a, b):
return a + b
if __name__ == '__main__':
print(add(int(argv[1]), int(argv[2])))
确保脚本是可执行的:
chmod +x add.py
现在你可以从终端运行它:
./add.py 2 3
5
如果你打算使它更复杂,我建议查看argparse。它比argv更强大。
英文:
If you want to run your function from the command line a lot, it may be cleanest to make it an executable script. On Linux:
#!/usr/bin/python3
from sys import argv
def add(a, b):
return a + b
if __name__ == '__main__':
print(add(int(argv[1]), int(argv[2])))
Make sure the script is executable:
chmod +x add.py
Now you can run it from the terminal:
./add.py 2 3
5
If you are going to make it more complex, I recommend checking out argparse. It's more powerful than argv
.
答案3
得分: 0
-
你需要先打开 Python 终端
-
定义函数
-
然后执行函数
你也可以在脚本文件中选择部分代码,然后使用<kbd>Shift</kbd>+<kbd>Enter</kbd>打开 Python 交互终端并执行代码。
你可以详细阅读Python 交互窗口。
另外,使用Jupyter Notebooks可能更方便。
英文:
You can also select part of the code in the script file, and then use <kbd>Shift</kbd>+<kbd>Enter</kbd> to open the python interactive terminal and execute the code.
You can read Python Interactive window in detail.
In addition, it may be more convenient to use Jupyter Notebooks.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论