How to protect python script from editing


I am building a python script for my co-workers to use.

what I want for my co-workers is to be able to run and view the script but not to edit the script when they download it from GitHub. I explored a few options like in this question and this article but unfortunately none of them is what I need.

The script functionality are as follows:

  1. perform certain calculation on a set of data with preset assumption and condition.
  2. write the result to an Excel file
  3. report the result.

Now, when my co-worker are using this script I do not want them to edit the code specifically the preset assumption and condition part, so that every one uses this script are using the same condition and assumption to perform calculation on the data and report the result back.

consider the following example:
say you have a script named
the contents of that script are:

def modified_multiplication(a: int, b: int):
    result = ((a * b) * 0.5) + 2
    return result 

now, the behavior I want is that the user can open the script and sees that multiplication is modified by first multiplying by 0.5 and then 2 is added but can not change these values for example to 0.7 and 3.
So, I am locking for a way that can achieve this behavior.

if it helps, I am using python 3.10 and pycharm editor.

Asked By: Adel Moustafa



I’m not sure if what you’re trying to do is possible.

Unfortunately, I don’t think it’s possible to disallow write access to a file. While you can locally restrict access to a file, once another user has the file on their own computer, it’s theirs to do whatever they want.

I want to make it clear that your coworkers cannot directly edit the github source code (unless they have access of course). What they do with their custom copy of the file is their business, it won’t change for anyone else.

However, if you want to prevent a user editing their own local file, your best bet is using chmod.

Using chmod

If you are on linux (or possibly mac), you can use the command line tool chmod to edit the attributes of a file. For example, to allow reading and execution of the file (but not write access), use the following command:

chmod a=rx

This is especially useful for shared servers where you don’t want people to accidentally overwrite key files.

However: if the user downloads the file on their local machine, they can always just use chmod to reverse the command and allow editing again. This does not stop developers editing local copies of the file.

Reversing chmod

If you want to make the file editable again, use the following command:

chmod a=rwx
Answered By: Dylan Rogers
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.