[英]How to give executable permission to all Python scripts in Linux?
假設我有一個名為a.py的 python 腳本,如下所示:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author : Bhishan Poudel
# Date : Jul 13, 2016
# Imports
# Script
print("hello")
我可以通過兩種方式運行這個腳本:
使用python解釋器:
python3 a.py
更改權限
chmod a+x a.py; ./a.py
問題
如何在不始終使用chmod a+x script_name
情況下運行任何新的或舊的 python 腳本。
我對我的計算機具有 root 訪問權限和用戶訪問權限。
基本上我想要所有 .py 文件的可執行權限,我們該怎么做?
我嘗試了不同的shebangs,例如:
#!/usr/bin/python3
#!/usr/bin/env python3
#!/usr/local/bin/python3
#!/usr/local/bin/env python3
python 解釋器也在 $PATH 中。 echo $PATH 的輸出如下:
/Library/Frameworks/Python.framework/Versions/2.7/bin:/Library/Frameworks/Python.framework/Versions/3.5/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/texbin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/Library/Frameworks/Python.framework/Versions/3.5/bin:/opt/local/bin:/Users/poudel/phosim:/Users/poudel/Applications:/usr/local/octave/3.8.0/bin:/Users/poudel/Applications/Geany.app/Contents/MacOS/:/opt/local/bin:/Users/poudel/phosim:/Users/poudel/Applications:/usr/local/octave/3.8.0/bin:/Applications/Geany.app/Contents/MacOS/:/opt/local/bin:/Users/poudel/phosim:/Users/poudel/Applications:/usr/local/octave/3.8.0/bin:/Applications/Geany.app/Contents/MacOS/
此外, ls /usr/bin/py* 具有:
/usr/bin/pydoc* /usr/bin/python2.5@ /usr/bin/pythonw*
/usr/bin/pydoc2.5@ /usr/bin/python2.5-config@ /usr/bin/pythonw2.5@
/usr/bin/pydoc2.6@ /usr/bin/python2.6@ /usr/bin/pythonw2.6@
/usr/bin/pydoc2.7@ /usr/bin/python2.6-config@ /usr/bin/pythonw2.7@
/usr/bin/python* /usr/bin/python2.7@
/usr/bin/python-config* /usr/bin/python2.7-config@
相關鏈接:
http://effbot.org/pyfaq/how-do-i-make-a-python-script-executable-on-unix.htm
在linux中執行python文件時權限被拒絕
python的bash權限被拒絕
通過bash啟動python腳本時權限被拒絕
艱難的道路
使用 root 權限在下面運行:
find /your/path/ -type f -name "*.py" -exec chmod u+x {} \;
注意:
如果您是.py
文件的所有者,則無需以 root 身份運行chmod
。
聰明的方式
寫一個腳本來解決這個問題。
#!/bin/bash
if [ -f "$1" ]
then
geany "$1" # You could also use xdg-open if you set geany to open .py files
else
cp /path/to/python/startup/template "$1" # You may omit this if you don't have a default template
chmod u+x "$1"
geany "$1"
fi
將腳本保存為pycreator
中的/usr/bin/
,然后執行
chown root:root /usr/bin/pycreator
chmod +x-w /usr/bin/pycreator
要使用pycreator
創建新腳本,請執行
pycreator calculator.py
使用@sjsam的想法,我做了以下事情:
假設我在任何位置都有一個文件 hello.py。
cd to that location
find $PWD -type f -name "*.py" -exec chmod u+x {} \;
./hello.py
# Now, i can create any number of .py files in that folder and run ./filename
# Note: if we are running as user permission, and also have sudo access,
we can also do:
sudo -H find $PWD -type f -name "*.py" -exec chmod u+x {} \;
We should not use sudo unless absolutely necessary.
感謝 sjsam。
只需在終端中輸入此命令即可。
sudo su
試試這個chmod +x *.py它適用於我的 PC(操作系統:Ubuntu 20.4),我也在使用#! /usr/bin/env python3 shebang
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.