Python programming on Pythonanywhere

  • Context: Python 
  • Thread starter Thread starter jbowers9
  • Start date Start date
  • Tags Tags
    Programming Python
Click For Summary

Discussion Overview

The discussion centers around running a Python script on the PythonAnywhere platform, specifically a script named "bonds.py" that requires a data file ("ethane.xyz") to be piped to it. Participants explore issues related to file input, command-line arguments, and the specific environment of PythonAnywhere.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Exploratory

Main Points Raised

  • One participant describes an attempt to run "bonds.py" with "ethane.xyz" but encounters issues, suggesting that the piping syntax or console context may be problematic.
  • Another participant requests the Python code that reads the data file to better understand the issue.
  • A participant provides a code snippet for the function that reads the file into a 2D array, indicating that the script has worked previously.
  • Several participants inquire about the specific error messages received when attempting to run the script, emphasizing the need for clarity on the error output.
  • One participant suggests that the user might be incorrectly invoking the script in the PythonAnywhere environment, proposing an alternative method of execution.
  • Another participant notes that the program seems to expect user input for the file name rather than command-line arguments, indicating a potential misunderstanding of how the script is designed to operate.

Areas of Agreement / Disagreement

Participants express uncertainty about the correct method to run the script on PythonAnywhere, with some suggesting different approaches and others questioning the script's design regarding input handling. No consensus is reached on the best solution.

Contextual Notes

There are indications of missing assumptions regarding the execution environment and how command-line arguments are processed in PythonAnywhere. The discussion reveals potential confusion about the expected input method for the script.

jbowers9
Messages
85
Reaction score
1
Hi all;
I've already posted to P_Anywhere's site but... I'm trying to run a script that needs a data file piped to it. Now P_ Anywhere gives you a resident directory and mine contains the program and the data file. Sooo...
bonds.py ethane.xyz maybe? Nah. Doesn't like that. But! I did get it to run before but can't remember how. Is someone familiar enough w/PythonAnywhere to show me the error of my ways?
1) The script does work, 2) The files are resident, 3) The piping syntax and/or what console I'm in may be the problem
 
Technology news on Phys.org
Can you post the Python code that is reading the data file? It's best if you enclose it with the code tags like the following:

Python:
print("Hello world")
 
Mentor note: Added code tags to preserve Python formatting, and altered some comment delimiters,
that were being misinterpreted as LaTex markers.
Python:
print("
# # IO FUNCTIONS # #

# read file data into a 2-d array
def get_file_string_array(file_name):
    try:
        file = open(file_name, "r")
    except IOError:
        print('Error: file (%s) not found!\n' % (file_name))
        sys.exit()
    lines = file.readlines()
    file.close()
    array = []
    for line in lines:
        array.append(line.split())
    return array")
Remainder of program follows. It's not mine, but as I've said it does work. I got it to work a few weeks ago.

Python:
import sys, math

# # CONSTANTS # #

# threshold beyond average of covalent radiii to determine bond cutoff
bond_thresh = 1.2

# covalent (or ionic) radii by atomic element (Angstroms) from
# "Inorganic Chemistry" 3rd ed, Housecroft, Appendix 6, pgs 1013-1014
cov_rads = {  'H' : 0.37, 'C' : 0.77, 'O' : 0.73, 'N' : 0.75, 'F' : 0.71,
  'P' : 1.10, 'S' : 1.03, 'Cl': 0.99, 'Br': 1.14, 'I' : 1.33, 'He': 0.30,
  'Ne': 0.84, 'Ar': 1.00, 'Li': 1.02, 'Be': 0.27, 'B' : 0.88, 'Na': 1.02,
  'Mg': 0.72, 'Al': 1.30, 'Si': 1.18, 'K' : 1.38, 'Ca': 1.00, 'Sc': 0.75,
  'Ti': 0.86, 'V' : 0.79, 'Cr': 0.73, 'Mn': 0.67, 'Fe': 0.61, 'Co': 0.64,
  'Ni': 0.55, 'Cu': 0.46, 'Zn': 0.60, 'Ga': 1.22, 'Ge': 1.22, 'As': 1.22,
  'Se': 1.17, 'Kr': 1.03, 'X' : 0.00}

# # IO FUNCTIONS # #

# read file data into a 2-d array
def get_file_string_array(file_name):
    try:
        file = open(file_name, "r")
    except IOError:
        print('Error: file (%s) not found!\n' % (file_name))
        sys.exit()
    lines = file.readlines()
    file.close()
    array = []
    for line in lines:
        array.append(line.split())
    return array

# read in geometry from xyz file
def get_geom(xyz_file_name):
    xyz_array = get_file_string_array(xyz_file_name)
    n_atoms = int(xyz_array[0][0])
    at_types = ['' for i in range(n_atoms)]
    coords = [[0.0 for j in range(3)] for i in range(n_atoms)]
    for i in range(n_atoms):
        at_types[ i] = xyz_array[i+2][0]
        for j in range(3):
            coords[ i][j] = float(xyz_array[i+2][j+1])
    geom = [at_types, coords]
    return geom

# input syntax and usage warnings
def get_inputs():
    if (not len(sys.argv) == 2):
        print('Usage: bonds.py XYZ_FILE\n')
        print('  XYZ_FILE: coordinates of target molecule\n')
        sys.exit()
    else:
        xyz_file_name = sys.argv[1]
        return xyz_file_name

# print geometry to screen
def print_geom(geom, comment):
    at_types, coords = geom[0:2]
    n_atoms = len(at_types)
    print('%i\n%s\n' % (n_atoms, comment), end='')
    for i in range(n_atoms):
        print('%-2s' % (at_types[ i]), end='')
        for j in range(3):
            print(' %12.6f' % (coords[ i][j]), end='')
        print('\n', end='')
    print('\n', end='')

# print bond graph to screen
def print_bond_graph(geom, bond_graph, comment):
    at_types = geom[0]
    n_atoms = len(at_types)
    print('%s\n' % (comment), end='')
    for i in range(n_atoms):
        print(' %4i %-2s -' % (i+1, at_types[I]), end='')
        for j in range(len(bond_graph[ i])):
            print(' %i' % (bond_graph[ i ][j] + 1), end='')
        print('\n', end='')
    print('\n', end='')

# print list of bond lengths to screen
def print_bonds(geom, bonds):
    at_types = geom[0]
    n_bonds = len(bonds)
    print('%i bond(s) found (Angstrom)' % (n_bonds))
    for q in range(n_bonds):
        n1, n2  = bonds[q][0:2]
        r12 = bonds[q][2]
        nstr = '%i-%i' % (n1+1, n2+1)
        tstr = '(%s-%s) ' % (at_types[n1], at_types[n2])
        print(' %-15s  %-13s    %6.4f\n' % (nstr, tstr, r12), end='')
    print('\n', end='')

# # MATH FUNCTIONS # #

# calculate distance between two 3-d cartesian coordinates
def get_r12(coords1, coords2):
    r2 = 0.0
    for p in range(3):
        r2 += (coords2[p] - coords1[p])**2
    r = math.sqrt(r2)
    return r

# # TOPOLOGY FUNCTIONS # #

# build graph of which atoms are covalently bonded
def get_bond_graph(geom):
    at_types, coords = geom[0:2]
    n_atoms = len(at_types)
    bond_graph = [[] for i in range(n_atoms)]
    for i in range(n_atoms):
        covrad1 = cov_rads[at_types[I]]
        for j in range(i+1, n_atoms):
            covrad2 = cov_rads[at_types[j]]
            thresh = bond_thresh * (covrad1 + covrad2)
            r12 = get_r12(coords[I], coords[j])
            if (r12 < thresh):
                bond_graph[I].append(j)
                bond_graph[j].append(i)
    return bond_graph

# determine atoms which are covalently bonded from bond graph
def get_bonds(geom, bond_graph):
    at_types, coords = geom[0:2]
    n_atoms = len(at_types)
    bonds = []
    for i in range(n_atoms):
        for a in range(len(bond_graph[ i])):
            j = bond_graph[I][a]
            if (i < j):
                r12 = get_r12(coords[I], coords[j])
                bonds.append([i, j, r12])
    return bonds

# # MAIN BLOCK # #

# read in geometry, determine bonded topology
xyz_file_name = get_inputs()
geom = get_geom(xyz_file_name)
bond_graph = get_bond_graph(geom)

# calculate bond lengths
bonds = get_bonds(geom, bond_graph)

# print resulting values
print_geom(geom, 'initial geometry')
print_bond_graph(geom, bond_graph, 'bond graph')
print_bonds(geom, bonds)

# end of program
 
Last edited by a moderator:
When you say it "Doesn't like that.", what error does it give? Are you sure the "ethane.xyz" file is in the same directory as "bonds.py"?
 
Usage: bonds.py XYZ_FILE XYZ_FILE: coordinates of target molecule Traceback (most recent call last): File "/home/jbowers9/bonds.py", line 138, in <module> xyz_file_name = get_inputs() File "/home/jbowers9/bonds.py", line 52, in get_inputs sys.exit()SystemExit>>> >>> /home/jbowers9/bonds.py /home/jbowers9/ethane.xyz
File "<stdin>", line 1 /home/jbowers9/bonds.py /home/jbowers9/ethane.xyz ^SyntaxError: invalid syntax

/home/jbowers9/bonds.py

/home/jbowers9/ethane.xyz
 
bonds.py ethane.xyz
File "<stdin>", line 1
bonds.py ethane.xyz
^
SyntaxError: invalid syntax
 
Sorry, I don't know enough about the pythonanywhere environment to understand what the problem is. Maybe someone else does. In a standard environment like unix you would type,

python bonds.py ethane.xyz

It looks like pythonanywhere invokes Python automatically. You might try:

bonds.py

and then after it comes back:

ethane.xyz
 
jbowers9 said:
Usage: bonds.py XYZ_FILE XYZ_FILE: coordinates of target molecule Traceback (most recent call last): File "/home/jbowers9/bonds.py", line 138, in <module> xyz_file_name = get_inputs() File "/home/jbowers9/bonds.py", line 52, in get_inputs sys.exit()SystemExit>>> >>> /home/jbowers9/bonds.py /home/jbowers9/ethane.xyz
File "<stdin>", line 1 /home/jbowers9/bonds.py /home/jbowers9/ethane.xyz ^SyntaxError: invalid syntax

/home/jbowers9/bonds.py

/home/jbowers9/ethane.xyz
It appears to me that you are trying to pass the name of the input file as a command line argument, but your program isn't set up to operate that way. What you're calling your "main block" has an input statement that expects the user to type in the name of the input file.

To have your program process command-line arguments, you need to import the argparse module, which is described in the Python docs.
 

Similar threads

  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 16 ·
Replies
16
Views
4K
  • · Replies 21 ·
Replies
21
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 11 ·
Replies
11
Views
3K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 27 ·
Replies
27
Views
5K
Replies
55
Views
7K