New FAMILUG

The PyMiers

Thursday 5 February 2015

[Python, bash] Kiểm tra file executable

Để kiểm tra xem đầu vào của nó có phải là một file chạy được không (như các file trong /bin, hay các file đã đươc chmod +x),
hacker mũ hồng viết như sau:

bash:
$ test -x path
python:
In [3]: os.access(path, os.X_OK)
Out[3]: True
Có gì sai ở đây?
manpage của "test" viết khá chi tiết về tác dụng của nó -x:
man 1 test:
$ man test | grep -A2 -- -x
     -x file       True if file exists and is executable.  True indicates only
                   that the execute flag is on.  If file is a directory, true
                   indicates that file can be searched.
-x ở bash hay os.access(path, os.X_OK) chỉ kiểm tra xem execute flag(--x) trong permission (ứng với user hiện tại) của "file" có được bật không. Nó không phân biệt đầu vào là một file bình thường hay một directory.

Sửa lại:
- đảm bảo đầu vào là 1 file bình thường (cũng có thể là 1 symlink)

Python:
In [17]: path = '/bin'

In [18]: os.access(path, os.X_OK) and os.path.isfile(path) or os.path.islink(path)
Out[18]: False
Bash:
$ path='/'
$ test -f $path && test -x $path ; echo $?
1 # thank to +Hiep Nguyen Van 
- hoặc đảm bảo đầu vào không phải là 1 directory.
Python:
In [19]: os.access(path, os.X_OK) and not os.path.isdir(path)
Out[19]: False
Bash:
$ path='/bin/cat'; test -x $path && test ! -d $path && echo $path is a executable file not a dir
/bin/cat is a executable file not a dir
PS:
File permissions biểu diễn trên Python:
In [20]: os.R_OK, os.W_OK, os.X_OK
Out[20]: (4, 2, 1)
Hết
hvn@familug.org

1 comment: