how to make a python or perl script portable to both linux and windows?

前端 未结 4 2229
再見小時候
再見小時候 2021-02-14 04:26

I was wondering how to make a python script portable to both linux and windows?

One problem I see is shebang. How to write the shebang so that the script can be run on

4条回答
  •  我寻月下人不归
    2021-02-14 05:18

    Make sure you don't handle files and directories as strings and simply concatenate them with a slash in between. Perl:

    $path = File::Spec->catfile("dir1", "dir2", "file")
    

    Remember that Windows has volumes:

    ($volume, $path, $file) = File::Spec->splitpath($full_path);
    @directories = File::Spec->splitdir($path);
    

    When running other programs, try to avoid involving the shell. In Perl, when you run a command with the system function, you can easily get it wrong with:

    $full_command = 'C:\Documents and Settings/program.exe "arg1" arg2'; # spaces alert!
    system($full_command);
    

    Instead, you can run system with a list as argument: the executable and the arguments being separate strings. In that case, the shell doesn't get involved and you don't get into trouble regarding shell escaping or spaces in file names.

    system('C:\Documents and Settings/program.exe', 'arg1', 'arg2');
    

    There's a bunch of portability nits documented in the perlport manual.

提交回复
热议问题