LoginSignup
3
2

More than 5 years have passed since last update.

Python3のシンタックスチェック

Posted at

はじめに

Python3 で、Perl の -c オプションのように文法チェックだけしたいときこういった方法があるとのことなので、それをちょっとラップしたスクリプトをつくろう。

スクリプト

$HOME/bin/pyck
#!/usr/bin/env perl

use strict;
use warnings;

&main;exit;

sub main {
    my $file = shift @ARGV;
    &USAGE unless $file && -r $file && `/usr/bin/file ${file}`=~/Python/;

    print `/usr/bin/env python3 -m py_compile ${file}`;

    if( $? == 0 ) {
        print $file . " syntax OK\n";
    }
    else {
        print $file . " had compilation errors.\n";
    }
}

sub USAGE {
    (my $name = $0) =~ s@.*/@@;

    print <<"HERE";
NAME
    ${name} -- python3 syntax check

USAGE
    ${name} file

HERE

    exit;
}
~/.bash_profile
export PATH=$PATH:$HOME/bin
設定
$ chmod +x ~/bin/pyck
$ . .bash_profile

使い方

第一引数にpythonスクリプトを与えてね
$ pyck temp.pl
NAME
    pyck -- python3 syntax check

USAGE
    pyck file

エラーがある場合
$ pyck ng.py
  File "ng.py", line 4
    🍣 = 'スシ'
    ^
SyntaxError: invalid character in identifier

ng.py had compilation errors.
問題ない場合
$ pyck ok.py
ok.py syntax OK

おわり

おわり:whale2:

 環境

## Mac
$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.12.5
BuildVersion:   16F73


## Python3
$ python3 --version
Python 3.6.1


## Perl5
$ perl -v | perl -nwle'print if/version/'
This is perl 5, version 12, subversion 1 (v5.12.1) built for darwin-thread-multi-2level

参考と注釈

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2