簡體   English   中英

在 IDLE 上創建 python 代碼,然后在 macOS 終端中使用它

[英]creating python code on IDLE then using it in macOS terminal

我想知道如何利用 IDLE 上的代碼在 macOS 終端中工作。 比如我創建了一個function 如: def multiplication_by_2(x): return 2 * x

並將 .py 文件保存在桌面文件夾中。

我想使用終端來測試各種情況,例如multipication_by_2(100)等,但是我不確定在終端中輸入哪些命令來實現這一點。

朝着這個方向的任何方向都會有所幫助。 謝謝你。

如果您詢問如何通過命令行將 arguments 發送到您的程序,python 的sys庫有一個名為argv的列表,其中包含從命令行傳遞的 arguments。 將此添加到您的 python 文件中:

from sys import argv
for argument in argv:
    print(multipication_by_2(int(argument))) # All arguments are strings by default

然后在命令行中,執行python file_name.py 20 50 1和您可能想嘗試的任何其他數字,程序將打印它的雙精度數。

注意:如果您的命令行python不存在,請嘗試python3

在代碼末尾試試這個:

number = int(str(input("Enter the number you would like to multiply by 2: ")))
multiplication_by_2(number)

這樣,您可以獲得用戶輸入。 然后,在終端中:

$ python3 <filename>.py

哪個應該產生 output:

Enter the number you would like to multiply: <your input, ex. 100>
200

希望解決了!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM