<p>please read carefully <a href="https://pymolwiki.org/index.php/Launching_From_a_Script" rel="nofollow noreferrer">Launching From a Script</a></p>
<p>lines after the phrase:</p>
<blockquote>
<p>For advanced users, the following PyMOL versions also allow to run PyMOL from an existing Python process:
.................
.......................
.............................</p>
</blockquote>
<p>To run your code just change the name of the script file to something
different from <code>pymol.py</code> (that would cause importing related errors)***** , let say <code>pymol_importing_python_code.py</code> and add Python Shebang at the top of the script to allow for shebang support on linux ***</p>
<pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-  #---&gt; this is not needed anymore In Python3 UTF8 is assumed so
</code></pre>
<p>Launch it with <code>./pymol_importing_python_code.py</code> (you need to mark the file as executable)</p>
<p>Your script contains a bug in :</p>
<pre><code>def process_pdb(pdb_path):
    print(f&quot;Loading PDB file: {pdb_path}&quot;)
    cmd.load(pdb_path)
    
    print(&quot;Removing chains except chain A...&quot;)
    cmd.remove(&quot;not chain A&quot;)
    
    print(&quot;Removing solvent molecules (water)...&quot;)
    cmd.remove(&quot;solvent&quot;)

    print(f&quot;Saving modified PDB file: {pdb_path}&quot;)
    
    save_path = pdb_path
    
    cmd.save(save_path)

</code></pre>
<p>just add <code>cmd.delete(&quot;all&quot;)</code> as last pymol command in the function</p>
<p>to get:</p>
<pre><code>def process_pdb(pdb_path):
    print(f&quot;Loading PDB file: {pdb_path}&quot;)
    cmd.load(pdb_path)
    
    print(&quot;Removing chains except chain A...&quot;)
    cmd.remove(&quot;not chain A&quot;)
    
    print(&quot;Removing solvent molecules (water)...&quot;)
    cmd.remove(&quot;solvent&quot;)

    print(f&quot;Saving modified PDB file: {pdb_path}&quot;)
    
    save_path = pdb_path
    
    cmd.save(save_path)
    
    cmd.delete(&quot;all&quot;)
</code></pre>
<p>Otherwise your active pymol instance will add the previous loaded .pdb to the new loaded one and you'll end up saving  obj1.pdb , obj1+obj2.pdb , and so on.</p>
<p>See <a href="https://pymolwiki.org/index.php/Delete" rel="nofollow noreferrer">Delete</a> :</p>
<blockquote>
<p>delete removes objects or selections matching an expression name, which can include wildcards.</p>
<p><strong>USAGE</strong><br />
<br />
<code>delete name </code> <br />
<code>delete all   # deletes all objects</code></p>
</blockquote>
<p>If you wish to run your code from PyMOL and not Python, have a look at the <a href="https://pymolwiki.org/index.php/Category:Script_Library" rel="nofollow noreferrer">PyMOL Script Library</a> and see where your code is different from them, but maybe its just about a naming problem see above ***** or see the <strong>ADDENDUM</strong> below.
In PyMOL you have the ability to run PyMol scripts usually they have  <code>.pml</code> extension and you can run  PyMol from a Python script <code>.py</code> and then you can also build PyMol plug-ins. The way you wrote your question</p>
<blockquote>
<p>I have had issues with incorporating python scripts into PyMOL before, and I haven't ran a script with more than one structure (much less an entire directory). Is this possible under PyMOL, and if so what is the error with my code in that case?</p>
</blockquote>
<p>could be misleading, so please apologize me if I got it wrong.</p>
<p><strong>ADDENDUM</strong></p>
<p>you get :</p>
<p><code>Error: failed to open file &quot;&quot;pymol_importing_python_code.py&quot;&quot;</code></p>
<p>because you type</p>
<p><code>PyMOL&gt; run &quot;pymol_importing_python_code.py&quot;</code> ;</p>
<p>instead of just</p>
<p><code>PyMOL&gt; run pymol_importing_python_code.py</code> . °°°</p>
<p><strong>Your script won't work in any case because the way it is written see here:</strong></p>
<p><em>To have your script to work from within PyMOL, remember the <code>cmd.delete('all')</code> bit</em></p>
<ol>
<li><p>remove the <strong><em>main</em>_ guard</strong>  (<code>if __name__ == '__main__':</code> line in your code) and you can run it with: <code>PyMOL&gt; run pymol.py</code> .</p>
</li>
<li><p>Or keep it the way it is and invoke it with: <code>PyMOL&gt; run pymol.py , main</code> ; see
<a href="https://pymolwiki.org/index.php/Run" rel="nofollow noreferrer">Run</a> in <a href="https://pymolwiki.org/index.php/Main_Page" rel="nofollow noreferrer">PyMOL Wiki! </a> for details</p>
</li>
</ol>
<p>Again have a look here for a better description of <a href="https://pymol.org/tutorials/scripting/howtorunscripts.html" rel="nofollow noreferrer">Part 2: How to run scripts conveniently...</a></p>
<p>°°° my bad wasn't able to read weel the pic you uploaded.</p>
<p>*** I know I am a newbie like you . but please do yourself a favour
and move to a linux distro (i.e. <a href="https://towardsdatascience.com/why-do-bioinformaticians-avoid-using-windows-c5acb034f63c" rel="nofollow noreferrer">Why do Bioinformaticians Avoid Using Windows? List of reasons why almost every bioinformatician use Linux instead of Windows</a>)</p>

CC BY-SA 4.0
2024-12-24T16:37:36.963Z
Brilliant! Merry Christmas @pippo1980
M__
CC BY-SA 4.0
2024-12-24T15:52:33.720Z
2024-12-25T23:57:42.340Z
2024-12-25T23:57:42.340Z
pippo1980
<pre><code>import os
from pymol import cmd

def process_pdb(pdb_path):
    print(f&quot;Loading PDB file: {pdb_path}&quot;)
    cmd.load(pdb_path)
    
    print(&quot;Removing chains except chain A...&quot;)
    cmd.remove(&quot;not chain A&quot;)
    
    print(&quot;Removing solvent molecules (water)...&quot;)
    cmd.remove(&quot;solvent&quot;)

    print(f&quot;Saving modified PDB file: {pdb_path}&quot;)
    save_path = pdb_path
    cmd.save(save_path)

def process_multiple_pdbs(pdb_directory):
    print(f&quot;Processing PDB files in directory: {pdb_directory}&quot;)
    for pdb_file in os.listdir(pdb_directory):
        if pdb_file.endswith('.pdb'):
            pdb_path = os.path.join(pdb_directory, pdb_file)
            pdb_path = pdb_path.replace(&quot;\\&quot;, &quot;\\\\&quot;)  
            print(f&quot;Processing: {pdb_file}&quot;)
            process_pdb(pdb_path)

if __name__ == '__main__':
    pdb_directory = &quot;C:\\Users\\khadi\\OneDrive\\Desktop\\positive6_directory&quot;
    print(&quot;Starting script...&quot;)
    process_multiple_pdbs(pdb_directory)
    print(&quot;Script execution completed.&quot;)
</code></pre>
<p>This is currently the code I'm using to load in all individual PDB files within my directory and deleting chains other than A and also deleting waters. My directories are quite large, so I would need to automate the process instead of doing it one by one. I've tried running this trough the GUI and Windows Terminal using .\PyMOLWin.exe too. Both times, there was no error that came up, but none of the printable commands I put into the code function. By manually checking the files within my directories, I discovered that the PDB files were still the same as they once were. However, I'm not receiving errors associated with my code.</p>
<p><a href="https://i.sstatic.net/0k2No6KC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/0k2No6KC.png" alt="The first command had an incorrect use of &quot;&quot;, but the second command was run without any errors attached, but did not complete the purpose of the code" /></a></p>
<p>The first command had an incorrect use of &quot;&quot;, but the second command was run without any errors attached, but did not complete the purpose of the code</p>
<p>I have had issues with incorporating python scripts into PyMOL before, and I haven't ran a script with more than one structure (much less an entire directory). Is this possible under PyMOL, and if so what is the error with my code in that case?</p>
<p>If it is not possible through PyMOL, what other tools could I use in this instance that would automate this process for me?</p>
<p>Thanks</p>

CC BY-SA 4.0
2024-12-27T03:07:20.223Z
Hi @Ashabul could kindly mark the question as answered, i.e. "accepted"? This is a good answer and would be etiquette within the site.
M__
<python><proteins><pymol>
Pymol automating chain and water deletion
# Pymol automating chain and water deletion

(Asked by: username_0 on 2024-12-23)

import os
from pymol import cmd

def process_pdb(pdb_path):
    print(f"Loading PDB file: {pdb_path}")
    cmd.load(pdb_path)
    
    print("Removing chains except chain A...")
    cmd.remove("not chain A")
    
    print("Removing solvent molecules (water)...")
    cmd.remove("solvent")

    print(f"Saving modified PDB file: {pdb_path}")
    save_path = pdb_path
    cmd.save(save_path)

def process_multiple_pdbs(pdb_directory):
    print(f"Processing PDB files in directory: {pdb_directory}")
    for pdb_file in os.listdir(pdb_directory):
        if pdb_file.endswith('.pdb'):
            pdb_path = os.path.join(pdb_directory, pdb_file)
            pdb_path = pdb_path.replace("\\", "\\\\")  
            print(f"Processing: {pdb_file}")
            process_pdb(pdb_path)

if __name__ == '__main__':
    pdb_directory = "C:\\Users\\khadi\\OneDrive\\Desktop\\positive6_directory"
    print("Starting script...")
    process_multiple_pdbs(pdb_directory)
    print("Script execution completed.")

This is currently the code I'm using to load in all individual PDB files within my directory and deleting chains other than A and also deleting waters. My directories are quite large, so I would need to automate the process instead of doing it one by one. I've tried running this trough the GUI and Windows Terminal using .\PyMOLWin.exe too. Both times, there was no error that came up, but none of the printable commands I put into the code function. By manually checking the files within my directories, I discovered that the PDB files were still the same as they once were. However, I'm not receiving errors associated with my code.

The first command had an incorrect use of "", but the second command was run without any errors attached, but did not complete the purpose of the code
I have had issues with incorporating python scripts into PyMOL before, and I haven't ran a script with more than one structure (much less an entire directory). Is this possible under PyMOL, and if so what is the error with my code in that case?
If it is not possible through PyMOL, what other tools could I use in this instance that would automate this process for me?
Thanks

**Tags:** python, proteins, pymol
> **Comments:**
> **username_1**: Hi @Ashabul could kindly mark the question as answered, i.e. "accepted"? This is a good answer and would be etiquette within the site.  

---

## 1 answers

### Answer by username_2 on 2024-12-24. Score: 2

please read carefully Launching From a Script
lines after the phrase:

For advanced users, the following PyMOL versions also allow to run PyMOL from an existing Python process:
.................
.......................
.............................

To run your code just change the name of the script file to something
different from pymol.py (that would cause importing related errors)***** , let say pymol_importing_python_code.py and add Python Shebang at the top of the script to allow for shebang support on linux ***
#!/usr/bin/env python3
# -*- coding: utf-8 -*-  #---> this is not needed anymore In Python3 UTF8 is assumed so

Launch it with ./pymol_importing_python_code.py (you need to mark the file as executable)
Your script contains a bug in :
def process_pdb(pdb_path):
    print(f"Loading PDB file: {pdb_path}")
    cmd.load(pdb_path)
    
    print("Removing chains except chain A...")
    cmd.remove("not chain A")
    
    print("Removing solvent molecules (water)...")
    cmd.remove("solvent")

    print(f"Saving modified PDB file: {pdb_path}")
    
    save_path = pdb_path
    
    cmd.save(save_path)


just add cmd.delete("all") as last pymol command in the function
to get:
def process_pdb(pdb_path):
    print(f"Loading PDB file: {pdb_path}")
    cmd.load(pdb_path)
    
    print("Removing chains except chain A...")
    cmd.remove("not chain A")
    
    print("Removing solvent molecules (water)...")
    cmd.remove("solvent")

    print(f"Saving modified PDB file: {pdb_path}")
    
    save_path = pdb_path
    
    cmd.save(save_path)
    
    cmd.delete("all")

Otherwise your active pymol instance will add the previous loaded .pdb to the new loaded one and you'll end up saving  obj1.pdb , obj1+obj2.pdb , and so on.
See Delete :

delete removes objects or selections matching an expression name, which can include wildcards.
USAGE

delete name  
delete all   # deletes all objects

If you wish to run your code from PyMOL and not Python, have a look at the PyMOL Script Library and see where your code is different from them, but maybe its just about a naming problem see above ***** or see the ADDENDUM below.
In PyMOL you have the ability to run PyMol scripts usually they have  .pml extension and you can run  PyMol from a Python script .py and then you can also build PyMol plug-ins. The way you wrote your question

I have had issues with incorporating python scripts into PyMOL before, and I haven't ran a script with more than one structure (much less an entire directory). Is this possible under PyMOL, and if so what is the error with my code in that case?

could be misleading, so please apologize me if I got it wrong.
ADDENDUM
you get :
Error: failed to open file ""pymol_importing_python_code.py""
because you type
PyMOL> run "pymol_importing_python_code.py" ;
instead of just
PyMOL> run pymol_importing_python_code.py . °°°
Your script won't work in any case because the way it is written see here:
To have your script to work from within PyMOL, remember the cmd.delete('all') bit

remove the main_ guard  (if __name__ == '__main__': line in your code) and you can run it with: PyMOL> run pymol.py .

Or keep it the way it is and invoke it with: PyMOL> run pymol.py , main ; see
Run in PyMOL Wiki!  for details


Again have a look here for a better description of Part 2: How to run scripts conveniently...
°°° my bad wasn't able to read weel the pic you uploaded.
*** I know I am a newbie like you . but please do yourself a favour
and move to a linux distro (i.e. Why do Bioinformaticians Avoid Using Windows? List of reasons why almost every bioinformatician use Linux instead of Windows)

> **Comments:**
> **username_1**: Brilliant! Merry Christmas @pippo1980  

---

