![](/img/trans.png)
[英]Make VS Code to execute python script in an already running terminal (Ubuntu)
[英]Create terminal name for execute python script in Ubuntu
我在“/home/username/scripts/pyscript”中有一個 python 文件,我想設置一個詞來直接執行這個腳本。
我想做這個“python3 /home/username/scripts/pyscript/main.py arg1 arg2”,但看起來像這個“myscript arg1 arg2”
這可能嗎? 還是非常感謝。
它可以通過多種方式實現。 鏈接適用於Bash ,據說是您的 shell 但這些想法始終適用。
第一個選項:制作 shell別名
alias myscript='python3 /home/username/scripts/pyscript/main.py'
請務必將別名添加到 your.profile 以使其在注銷后仍然有效。
第二個選項:定義一個包裝腳本。 創建一個包含以下內容的文件,以您想要的命令命名(例如 myscript):
#!/bin/bash
python3 /home/username/scripts/pyscript/main.py "$@"
保存並使其可執行,然后調用它:
chmod +x myscript
./myscript arg1 arg2
確保將腳本復制到 PATH 中的文件夾中(使用 echo $PATH 檢查位置),以便能夠從任何文件夾中調用它。
您還可以使用pyinstaller
創建單個文件可執行文件:
第 1 步:安裝pyinstaller
[注意:最佳做法是在virutalenv
中執行此操作]
$ pip install pyinstaller
第 2 步:針對您的腳本運行pyinstaller
$ pyinstaller --console --onefile /home/username/scripts/pyscript
$ pyinstaller pyscript.spec # use this after the first run
第三步:測試生成的可執行文件
$ cd /home/username/scripts/dist # generated by pyinstaller
$ pyscript arg1 arg2
第 4 步:利用 $PATH 變量
$ cp /home/username/scripts/dist/pyscript /usr/bin
您現在應該能夠從任何地方運行可執行文件。
應該注意的是,生成的可執行文件是特定於操作系統的。 例如,如果您在 Ubuntu 機器上生成它,它將僅在 Ubuntu(基於 Debian)上運行。 Windows 和其他 Linux 發行版也是如此。
最后我在@pierpaciugo 的幫助下求解我在.bashrc 的末尾添加了一個別名以使其持久化:
alias create='bash /home/username/Programming/Python/GithubAPI/script.sh'
我不能只使用別名,因為我的 python 依賴於虛擬環境,所以如果我嘗試這個,我無法將參數添加到我的 python 腳本中。
為此,我創建了這個 bash 腳本:
#!/bin/bash
source /home/username/Programming/Python/GithubAPI/venv/bin/activate && python3 /home/username/Programming/Python/GithubAPI/main.py $@ && deactivate
現在我可以編寫“create param1 param2”並且它可以工作。 我正在使用所有全局路徑,但將腳本添加到我的 PATH 中的文件夾中可能是個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.