How can I ignore MOTD and Banner messages with my Python/Paramiko script? - stdout

I have a script that reads a host.csv file with IP addresses and connects to each server in turn and runs some commands. I want the output to go to a file name that I specify in a raw_input in the script. Right now I just print the output, but I want to save all of the output to a file, EXCEPT for the login information(BANNER / MOTD) and the timestamps that occur. I have been working on trying to make it only print the output of the actual commands that I am running on each box, but I haven't been able to make it work.
I've been programming with Python for about 3 months now, and I have had some success but sometimes I run into road blocks that I can't yet work my way through.
from __future__ import print_function
import threading
import paramiko
import getpass
import time
import os
import sys
os.system('clear')
class ssh(object):
shell = None
client = None
transport = None
def __init__(self, address, username, password):
print('Connecting to server on ip', str(address) + '.')
self.client = paramiko.client.SSHClient()
self.client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
self.client.connect(address, username=username, password=password, look_for_keys=False)
self.transport = paramiko.Transport((address, 22))
self.transport.connect(username=username, password=password)
thread = threading.Thread(target=self.process)
thread.daemon = True
thread.start()
def close_connection(self):
if(self.client != None):
self.client.close()
self.transport.close()
def open_shell(self):
self.shell = self.client.invoke_shell()
#self.shell.recv(1000)
def send_shell(self, command):
if(self.shell):
self.shell.send(command + '\n')
else:
print("Shell not opened.")
def process(self):
while True:
# Print data when available
if self.shell is not None and self.shell.recv_ready():
alldata = self.shell.recv(1024)
while self.shell.recv_ready():
alldata += self.shell.recv(1024)
data = alldata.split(os.linesep)
for line in data:
print(line)
header = "################## WHAT DO YOU WANT TO DO?? ##################"
headlen = len(header) - 2
secondline = "|" + (" " * headlen) + "|"
thirdline = "|" + " 1. Run the daily ATM Script." + (" " * 30) + "|"
fourthline = "|" + " 2. Run a single command on the entire ATM network" + (" " * 9) + "|"
print(header)
print(secondline)
print(secondline)
print(thirdline)
print(fourthline)
print(secondline)
print(secondline)
print("#" * len(header))
choice = raw_input("Choose your destiny: ")
while choice:
if choice == "1":
print(' \n##### STARTING PROGRAM #####\n')
sshUsername = getpass.getpass(prompt='ENTER USERNAME: ')
sshPassword = getpass.getpass('ENTER PASSWORD: ')
filename = raw_input("What filename dost thou chooseth?")
writefile = open(filename, 'a')
def main():
with open("host.csv", "r") as r:
for address in r:
print(address)
try:
connection = ssh(address, sshUsername, sshPassword)
try:
connection.open_shell()
time.sleep(1)
connection.send_shell('hardware cecplus timing references show')
time.sleep(1)
connection.send_shell('power')
time.sleep(1)
connection.send_shell('hard port show')
time.sleep(1)
connection.send_shell('sig show')
time.sleep(1)
connection.send_shell('conn spvcc pp show')
time.sleep(1)
connection.send_shell('interface sonet path near total')
time.sleep(1)
except:
print('Failed to run commands on:', r)
except:
print('Failed connection to:', r)
time.sleep(5)
connection.close_connection()
main()
elif choice == "2":
COMMAND = raw_input("INPUT A SINGLE COMMAND TO RUN ON THE ENTIRE ATM NETWORK:" )
if __name__ == '__main__':
print(' \n##### STARTING PROGRAM #####\n')
sshUsername = getpass.getpass(prompt='ENTER USERNAME: ')
sshPassword = getpass.getpass('ENTER PASSWORD: ')
def main():
with open("host.csv", "r") as r:
for address in r:
print(address)
try:
connection = ssh(address, sshUsername, sshPassword)
try:
connection.open_shell()
time.sleep(1)
connection.send_shell(COMMAND)
time.sleep(1)
except:
print('Failed to run commands on:', r)
except:
print('Failed connection to:', r)
time.sleep(1)
connection.close_connection()
main()
else:
print("If thou dost not Enter 1 or 2 thou willest not proceed")
choice = input("Choose your destiny: ")
The current results just print everything, including the banner and motd. If I can get it to only print the output from the commands I know I can write those outputs to a file. I basically want to ignore the MOTD and Banner messages.

Related

Part of requested market data is not subscribed-ib_insync

I have a problem with getting option parameters using the library ib_insync.
import time
from ib_insync import *
import pandas as pd
from configparser import ConfigParser
from ibapi.common import TickerId, SetOfFloat, SetOfString, MarketDataTypeEnum
config = ConfigParser()
# TWs 7497, IBGW 4001
def get_chain(ib,ticker, exp_list):
exps = {}
df = pd.DataFrame(columns=['strike', 'kind', 'close', 'last'])
for i in exp_list:
ib.sleep()
cds = ib.reqContractDetails(Option(ticker, i, exchange='SMART'))
options = [cd.contract for cd in cds]
tickers = [t for i in range(0, len(options), 100)
for t in ib.reqTickers(*options[i:i + 100])]
for x in tickers:
df = df.append(
{'strike': x.contract.strike, 'kind': x.contract.right, 'close': x.close, 'last': x.last, 'bid': x.bid,
'ask': x.ask, 'mid': (x.bid + x.ask) / 2, 'volume': x.volume}, ignore_index=True)
exps[i] = df
return exps
def get_individual(ib,ticker, exp, strike, kind):
cds = ib.reqContractDetails(Option(ticker, exp, strike, kind, exchange='SMART'))
options = [cd.contract for cd in cds]
tickers = [t for i in range(0, len(options), 100) for t in ib.reqTickers(*options[i:i + 100])]
con = {'strike': tickers[0].contract.strike, 'kind': tickers[0].contract.right, 'close': tickers[0].close,
'last': tickers[0].last, 'bid': tickers[0].bid, 'ask': tickers[0].ask, 'volume': tickers[0].volume}
return con
def main():
with IB().connect('127.0.0.1', 7497) as ib:
ib.reqMarketDataType(3)
time.sleep(1)
print(get_chain(ib,"AAPL", ["20220211"]))
if __name__ == '__main__':
main()
Output: "Error 10090, reqId 4: Part of requested market data is not subscribed. Subscription-independent ticks are still active.Delayed market data is available.AAPL NASDAQ.NMS/TOP/ALL"
My solution was to implement ib.sleep because I thought maybe the calls are overlapping. As you can see the MarketDataType is set to 3.
In the end a table with strikes and all other parameters are NaN. Sometimes the first row gets some values, because of this I think it is some kind of overlapping problem.
Sorry if my question is to long.

Shunting-yard with functions

I'm trying to parse a text with the Shunting-yard algorithm but I've come across a problem. I don't know where to start parsing functions.
This is my goal: print('Hello ' + in())
The current tokens:
[ID print, LPAREN, STRING "Hello ", PLUS, ID in, LPAREN, RPAREN, RPAREN]
My current parser:
class Parser:
def __init__(self, tokens:list, variables:dict):
self.tokens = tokens
self.idx = -1
self.tok = None
self.variables = variables
self.value_stack = []
self.operator_stack = []
self.next_token()
def next_token(self):
self.idx += 1
self.tok = self.tokens[self.idx] if self.idx < len(self.tokens) else None
def pop(self):
newop = self.operator_stack.pop()
val1 = self.value_stack.pop()
val2 = self.value_stack.pop()
self.value_stack.append(eval_(val1, val2, newop))
def parse(self):
while self.tok:
if self.tok.type in VALUE_TYPE:
self.value_stack.append(self.tok.value)
elif self.tok.type == TT_ID:
self.id()
continue
elif self.tok.type == TT_LPAREN:
self.operator_stack.append(TT_LPAREN)
elif self.tok.type in OPERATORS:
op = self.tok.type
while self.operator_stack and PRESCEDENCE.get(self.operator_stack[-1], 0) >= PRESCEDENCE.get(op, 0):
self.pop()
self.operator_stack.append(op)
elif self.tok.type == TT_RPAREN:
while self.operator_stack and self.operator_stack[-1] != TT_LPAREN:
self.pop()
self.operator_stack.pop()
self.next_token()
while self.operator_stack:
self.pop()
return self.value_stack[-1] if self.value_stack else None
def id(self):
tok = self.tok
self.next_token()
if not self.tok: return
if self.tok.type == TT_EQUALS:
self.next_token()
self.variables[tok.value] = self.parse()
elif self.tok.type == TT_LPAREN:
self.operator_stack.append(tok.value)
else:
self.value_stack.append(self.variables.get(tok.value, 'null'))
How would I implement function handling? Every time I try to execute a function I get this error:
Traceback (most recent call last):
File "lang.py", line 19, in <module>
out = evaluate(text, variables)
File "lang.py", line 10, in evaluate
parser.parse()
File "parsing.py", line 85, in parse
self.pop()
File "parsing.py", line 52, in pop
val2 = self.value_stack.pop()
IndexError: pop from empty list
Any help is appreciated.

hf-tikz and sphinx are not playing well together

I am trying to add some color to my matrices in sphinx. I was using hf-tikz for it before. However, when I add it to Sphinx, it renders it incorrectly.
The result that I am trying to get is
The result I am getting is
Here is the code that I have.
main.rst:
.. math::
\left(\begin{array}{cc}
\tikzmarkin[style red]{a}a\tikzmarkend{a}
& \tikzmarkin[style green]{b}b\tikzmarkend{b} \\
\tikzmarkin[style blue]{c}c\tikzmarkend{c}
& \tikzmarkin[style orange]{d}d\tikzmarkend{d} \\
\end{array}\right)
\star
\left(\begin{array}{cc}
\tikzmarkin[style red]{w}w\tikzmarkend{w}
& \tikzmarkin[style green]{x}x\tikzmarkend{x} \\
\tikzmarkin[style blue]{y}y\tikzmarkend{y}
& \tikzmarkin[style orange]{z}z\tikzmarkend{z} \\
\end{array}\right)
=
\left(\begin{array}{cc}
\tikzmarkin[hor=style red]{aw}{a\star w}\tikzmarkend{aw}
& \tikzmarkin[hor=style green]{bx}b\star x\tikzmarkend{bx} \\
\tikzmarkin[hor=style blue]{cy}c\star y\tikzmarkend{cy}
& \tikzmarkin[hor=style orange]{dz}d\star z\tikzmarkend{dz} \\
\end{array}\right)
conf.py
extensions = [
'sphinx.ext.imgmath',
]
# Math configurations (https://tex.stackexchange.com/a/69770/51173)
imgmath_image_format = 'svg'
imgmath_use_preview = True
imgmath_latex_preamble = r'''
\usepackage{xcolor}
\usepackage[customcolors]{hf-tikz}
\colorlet{myred}{red!50!purple!30}
\colorlet{mygreen}{green!50!lime!60}
\colorlet{myblue}{blue!50!white!50}
\colorlet{myorange}{orange!80!red!60}
\colorlet{mycyan}{cyan!90!blue!60}
\colorlet{mymagenta}{magenta!90!red!60}
\tikzset{
style red/.style={
set fill color=myred,
set border color=white,
},
style green/.style={
set fill color=mygreen,
set border color=white,
},
style blue/.style={
set fill color=myblue,
set border color=white,
},
style orange/.style={
set fill color=myorange,
set border color=white,
},
style cyan/.style={
set fill color=mycyan,
set border color=white,
},
style magenta/.style={
set fill color=mymagenta,
set border color=white,
},
%
hor/.style={
above left offset={-0.15,0.31},
below right offset={0.15,-0.125},
#1
},
ver/.style={
above left offset={-0.1,0.3},
below right offset={0.15,-0.15},
#1
}
}
'''
Makefile
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
#$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
#$(SPHINXBUILD) -M $# "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
make.bat
#ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
if "%1" == "" goto help
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd
EDIT: Added makefile used to build the rst's
I think I found why this was happening: the problem was in the sphinx.ext.imgmath extension + hf-tikz not working well with the DVI files.
When converting the math equations, sphinx creates a very basic latex document, and compiles it using latexpdf into a DVI file. After that the file is converted into an SVG, and the resulting svg file is copied to the sphinx's _build directory. The problem is that dvisvgm (used by imgmath) cannot convert tikz stuff. Alternative would be using extended DVI, but that doesn't work well either.
The solution is to compile everything into PDF, and convert that pdf into SVG. This is slightly problematic, and the only way I found is to use pdf2svg + pdfcrop. I ended up modifying the imgmath.py into a custom extension. Below are the changes that I put in the imgmath.py. The changes require the use of external applications, so I don't think there is a merit in creating a pull request (at least not with a more scalable solution).
Changes in the imgmath.py:
Create a new method:
def convert_pdf_to_svg(pdfpath, builder):
# type: (str, Builder) -> Tuple[str, int]
"""Convert DVI file to SVG image."""
tempdir = ensure_tempdir(builder)
filename = path.join(tempdir, 'math.svg')
name = 'pdfcrop'
command = [name, pdfpath, pdfpath]
run_external_command(command, name)
name = 'pdf2svg'
command = [name, pdfpath, filename]
run_external_command(command, name)
return filename, None
In the compile_math function, inside the try block, replace the return statement with the following
if builder.config.imgmath_pdf2svg:
return path.join(tempdir, 'math.pdf')
else:
return path.join(tempdir, 'math.dvi')
Inside the render_math method, in the block titles # .dvi -> .png/svg, replace the try block with the following
try:
if image_format == 'png':
imgpath, depth = convert_dvi_to_png(dvipath, self.builder)
elif image_format == 'svg':
if self.builder.config.imgmath_pdf2svg:
imgpath, depth = convert_pdf_to_svg(dvipath, self.builder)
else:
imgpath, depth = convert_dvi_to_svg(dvipath, self.builder)
except InvokeError:
self.builder._imgmath_warned_image_translator = True # type: ignore
return None, None
Finally, add a new configuration entry in the very end of the imgmath.py:
app.add_config_value('imgmath_pdf2svg', False, 'html')
After that, you can write in the conf.py to enable the tikz images.
imgmath_image_format = 'svg'
imgmath_latex = 'latexmk'
imgmath_latex_args = ['-pdf']
imgmath_pdf2svg = True # Available only in the custom `imgmath.py`
patch for imgmath extension. Includes some other stuff :)
The patch goes a->b.
--- a/imgmath.py
+++ b/imgmath.py
## -15,7 +15,7 ##
import sys
import tempfile
from hashlib import sha1
-from os import path
+from os import path, symlink
from subprocess import CalledProcessError, PIPE
from typing import Any, Dict, List, Tuple
## -157,6 +157,11 ##
with open(filename, 'w', encoding='utf-8') as f:
f.write(latex)
+ for add_file in builder.config.imgmath_latex_additional_files:
+ filename = path.join(tempdir, path.basename(add_file))
+ if not path.exists(filename):
+ symlink(path.join(builder.confdir, add_file), filename)
+
# build latex command; old versions of latex don't have the
# --output-directory option, so we have to manually chdir to the
# temp dir to run it.
## -165,9 +170,15 ##
command.extend(builder.config.imgmath_latex_args)
command.append('math.tex')
+ output_extension = 'dvi'
+ if builder.config.imgmath_latex == 'xelatex':
+ output_extension = 'xdv'
+ if builder.config.imgmath_pdf2svg:
+ output_extension = 'pdf'
+
try:
subprocess.run(command, stdout=PIPE, stderr=PIPE, cwd=tempdir, check=True)
- return path.join(tempdir, 'math.dvi')
+ return path.join(tempdir, 'math.' + output_extension)
except OSError:
logger.warning(__('LaTeX command %r cannot be run (needed for math '
'display), check the imgmath_latex setting'),
## -177,7 +188,7 ##
raise MathExtError('latex exited with error', exc.stderr, exc.stdout)
-def convert_dvi_to_image(command: List[str], name: str) -> Tuple[bytes, bytes]:
+def run_external_command(command: List[str], name: str) -> Tuple[bytes, bytes]:
"""Convert DVI file to specific image format."""
try:
ret = subprocess.run(command, stdout=PIPE, stderr=PIPE, check=True)
## -203,7 +214,7 ##
command.append('--depth')
command.append(dvipath)
- stdout, stderr = convert_dvi_to_image(command, name)
+ stdout, stderr = run_external_command(command, name)
depth = None
if builder.config.imgmath_use_preview:
## -227,7 +238,7 ##
command.extend(builder.config.imgmath_dvisvgm_args)
command.append(dvipath)
- stdout, stderr = convert_dvi_to_image(command, name)
+ stdout, stderr = run_external_command(command, name)
depth = None
if builder.config.imgmath_use_preview:
## -239,6 +250,21 ##
break
return filename, depth
+
+def convert_pdf_to_svg(pdfpath, builder):
+ # type: (str, Builder) -> Tuple[str, int]
+ """Convert DVI file to SVG image."""
+ tempdir = ensure_tempdir(builder)
+ filename = path.join(tempdir, 'math.svg')
+
+ name = 'pdfcrop'
+ command = [name, pdfpath, pdfpath]
+ run_external_command(command, name)
+
+ name = 'pdf2svg'
+ command = [name, pdfpath, filename]
+ run_external_command(command, name)
+ return filename, None
def render_math(self: HTMLTranslator, math: str) -> Tuple[str, int]:
## -291,7 +317,10 ##
if image_format == 'png':
imgpath, depth = convert_dvi_to_png(dvipath, self.builder)
elif image_format == 'svg':
- imgpath, depth = convert_dvi_to_svg(dvipath, self.builder)
+ if self.builder.config.imgmath_pdf2svg:
+ imgpath, depth = convert_pdf_to_svg(dvipath, self.builder)
+ else:
+ imgpath, depth = convert_dvi_to_svg(dvipath, self.builder)
except InvokeError:
self.builder._imgmath_warned_image_translator = True # type: ignore
return None, None
## -396,8 +425,10 ##
['-gamma', '1.5', '-D', '110', '-bg', 'Transparent'],
'html')
app.add_config_value('imgmath_dvisvgm_args', ['--no-fonts'], 'html')
+ app.add_config_value('imgmath_pdf2svg', False, 'html')
app.add_config_value('imgmath_latex_args', [], 'html')
app.add_config_value('imgmath_latex_preamble', '', 'html')
+ app.add_config_value('imgmath_latex_additional_files', [], 'html')
app.add_config_value('imgmath_add_tooltips', True, 'html')
app.add_config_value('imgmath_font_size', 12, 'html')
app.connect('build-finished', cleanup_tempdir)

Making a print function repeat on a new line everytime it prints

So I want this final print function to print its function on a new line every time it prints. I've tried various "\n" placements to make it work but to no avail. Any tips?
from datetime import date
currentYear = date.today().year
print('Hi. What is your name?')
name = input()
while True:
try:
print('How old are you, ' + name + '?')
age = int(input())
if age >= 0:
break
else:
print('That is not a valid number.')
except ValueError:
print('That is not a valid number')
ageinHundred = 100 - int(age)
y = currentYear + int(ageinHundred)
t = 'You will be 100 years old in the year ' + str(int((y)))
print(t)
print('Give me another number')
num = input()
f = (int(num) * t)
print(f)
I want the final print function (print(f)) to print f multiple times on a new line each time. Not one after the other like the above code does now.
Thanks!
Change the last couple of lines to:
# Put t inside a list so it does list multiplication instead
# of string multiplication
f = int(num) * [t]
# Then join the individual f-lists with newlines and print
print("\n".join(f))
For the f = line, inspect f to get a better idea of what's going on there.
For the join part, join takes a list of strings, inserts the given string (in this case "\n"; a newline), and "joins" it all together. Get used to using join. It is a very helpful function.
Try this:
from datetime import date
currentYear = date.today().year
print('Hi. What is your name?')
name = input()
while True:
try:
print('How old are you, ' + name + '?')
age = int(input())
if age >= 0:
break
else:
print('That is not a valid number.')
except ValueError:
print('That is not a valid number')
ageinHundred = 100 - int(age)
y = currentYear + int(ageinHundred)
t = 'You will be 100 years old in the year ' + str(int((y)))
print(t)
print('Give me another number')
num = input()
for i in range(0,int(num)):
print(t)

How can I get the length of a protein chain from a PDB file with Biopython?

I have tried it this way first:
for model in structure:
for residue in model.get_residues():
if PDB.is_aa(residue):
x += 1
and then that way:
len(structure[0][chain])
But none of them seem to work...
Your code should work and give you the correct results.
from Bio import PDB
parser = PDB.PDBParser()
pdb1 ='./1bfg.pdb'
structure = parser.get_structure("1bfg", pdb1)
model = structure[0]
res_no = 0
non_resi = 0
for model in structure:
for chain in model:
for r in chain.get_residues():
if r.id[0] == ' ':
res_no +=1
else:
non_resi +=1
print ("Residues: %i" % (res_no))
print ("Other: %i" % (non_resi))
res_no2 = 0
non_resi2 = 0
for model in structure:
for residue in model.get_residues():
if PDB.is_aa(residue):
res_no2 += 1
else:
non_resi2 += 1
print ("Residues2: %i" % (res_no2))
print ("Other2: %i" % (non_resi2))
Output:
Residues: 126
Other: 99
Residues2: 126
Other2: 99
Your statement
print (len(structure[0]['A']))
gives you the sum (225) of all residues, in this case all amino acids and water atoms.
The numbers seem to be correct when compared to manual inspection using PyMol.
What is the specific error message you are getting or the output you are expecting? Any specific PDB file?
Since the PDB file is mostly used to store the coordinates of the resolved atoms, it is not always possible to get the full structure. Another approach would be use to the cif files.
from Bio import PDB
parser = PDB.PDBParser()
pdb1 ='./1bfg.cif'
m = PDB.MMCIF2Dict.MMCIF2Dict(pdb1)
if '_entity_poly.pdbx_seq_one_letter_code' in m.keys():
print ('Full structure:')
full_structure = (m['_entity_poly.pdbx_seq_one_letter_code'])
print (full_structure)
print (len(full_structure))
Output:
Full structure:
PALPEDGGSGAFPPGHFKDPKRLYCKNGGFFLRIHPDGRVDGVREKSDPHIKLQLQAEERGVVSIKGVSANRYLAMKEDGRLLASKSVTDECFFFERLESNNYNTYRSRKYTSWYVALKRTGQYKLGSKTGPGQKAILFLPMSAKS
146
For multiple chains:
from Bio import PDB
parser = PDB.PDBParser()
pdb1 ='./4hlu.cif'
m = PDB.MMCIF2Dict.MMCIF2Dict(pdb1)
if '_entity_poly.pdbx_seq_one_letter_code' in m.keys():
full_structure = m['_entity_poly.pdbx_seq_one_letter_code']
chains = m['_entity_poly.pdbx_strand_id']
for c in chains:
print('Chain %s' % (c))
print('Sequence: %s' % (full_structure[chains.index(c)]))
It's just:
from Bio.PDB import PDBParser
from Bio import PDB
pdb = PDBParser().get_structure("1bfg", "1bfg.pdb")
for chain in pdb.get_chains():
print(len([_ for _ in chain.get_residues() if PDB.is_aa(_)]))
I appreciated Peters' answer, but I also realized the res.id[0] == " " is more robust (i.e. HIE). PDB.is_aa() cannot detect HIE is an amino acid while HIE is ε-nitrogen protonated histidine. So I recommend:
from Bio import PDB
parser = PDB.PDBParser()
pdb1 ='./1bfg.pdb'
structure = parser.get_structure("1bfg", pdb)
model = structure[0]
res_no = 0
non_resi = 0
for model in structure:
for chain in model:
for r in chain.get_residues():
if r.id[0] == ' ':
res_no +=1
else:
non_resi +=1
print ("Residues: %i" % (res_no))
print ("Other: %i" % (non_resi))
I think you would actually want to do something like
m = Bio.PDB.MMCIF2Dict.MMCIF2Dict(pdb_cif_file)
if '_entity_poly.pdbx_seq_one_letter_code' in m.keys():
full_structure = m['_entity_poly.pdbx_seq_one_letter_code']
chains = m['_entity_poly.pdbx_strand_id']
for c in chains:
for ci in c.split(','):
print('Chain %s' % (ci))
print('Sequence: %s' % (full_structure[chains.index(c)]))

Resources