I have two scripts main.py and get_number.py. The script get_number.py returns a random number whenver it's called. I want to call this script from main.py and print all these returned values. In other words, the script get_number.py is the following:
def get_random():
return np.random.uniform(0,1)
Now I have the following code in main.py
import get_number
n_call = 4
values = np.zeros(n_call)
for i in range(n_call):
values[i]= get_number.get_random()
print(values)
However I am receiving the error that No module named get_number. How would I go about accomplishing this task?
I believe you can import just as importing another libraries
from file1 import *
Importing variables from another file?
I Found some similar Problems up here
You are confusing between get_number and get_random
main.py:
import numpy as np
from get_number import get_random
n_call = 4
values = np.zeros(n_call)
for i in range(n_call):
values[i]= get_random()
print(values)
Out: [ 0.63433276 0.36541908 0.83485925 0.59532567]
get_number:
import numpy as np
def get_random():
return np.random.uniform(0,1)
You have to import this way:
In main.py
from get_number import get_random
n_call = 4
values = np.zeros(n_call)
for i in range(n_call):
values[i]= get_random()
print(values)
Related
I want to add a chain with all the residues and one carbon-alpha atom per residue using the OpenMM. Here the link of instances can be used openMM documentation . Currently I have one chain in my pdb file pdb file. Here is what I've tried:
from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *
import numpy as np
import mdtraj as md
# Here I remove all other atoms except carbon-alpha and stored them in a new file 'CA_only.pdb'
main_pdb = md.load_pdb('1PGB.pdb')
atoms_to_keep = [atom.index for atom in main_pdb.topology.atoms if atom.name == 'CA']
new_pdb = main_pdb.atom_slice(atoms_to_keep)
new_pdb.save('CA_only.pdb')
# Then I try to add a chain and residue, but no results
pdb = PDBFile('CA_only.pdb')
top = topology.Topology
chain=top.addChain(id='A')
residue = top.addResidue(MET, 0)
I might be using wrong names of residues. But I don't know what is wrong. Could someone have any idea how to resolve this? Thanks!!
I have two scripts
script_1.py
import sys
import math
from datetime import datetime, timedelta
from calendar import isleap
count = sys.argv[1]
state = sys.argv[2]
f = open("myfile_c_"+count+".xml", 'a')
f.write("<state >"+state+"state "+"\n")
f.close()
it creates files (copies of a file) according to the input count variable
script_2.py
import random
import subprocess
import decimal
import string
import sys
import math
from datetime import datetime, timedelta
from calendar import isleap
copy = int(sys.argv[1])
count = 0
state = random.choices( ["FeeSimple","Leasehold","Other"], weights=(80, 15, 5), k=copy)
while (count < copy):
exec(open("script_1.py count state[int(count]").read()) // should call the first script and enter the arguments
any idea how to call the first script from the second script and enter the arguments in the while loop ?
in top of script_2.py put the line below,else, you have another variable in your script_2.py called count so change one of them into another name to avoid bug.
from script_1 import count
I have a .py file with a function that calculates the gradient of a function at a point and returns the value of that gradient at the point. The function takes a np.array([2,]) as input and outputs another np.array([2,]). I am confused as to how I can call the function from the cmd line and run the function with a specified input.
Here is a code snippet:
import numpy as np
def grad(x):
x_1 = x[0]
x_2 = x[1]
df_dx_1 = 6*x
df_dx_2 = 8*x_2
df_dx = np.array([df_dx_1, df_dx_2])
return np.transpose(df_dx)
I would really appreciate your help!
EDIT: This question differs from the popular command line thread because I have a specific issue of not being able to recognise the numpy input
First change script to (Here it uses if __name__='__main__' to check if it is running from script, then import sys and pass first argument using sys.argv[0] to the function):
import numpy as np
def grad(x):
x_1 = x[0]
x_2 = x[1]
df_dx_1 = 6*x
df_dx_2 = 8*x_2
df_dx = np.array([df_dx_1, df_dx_2])
return np.transpose(df_dx)
if __name__ == '__main__':
import sys
grad(sys.argv[1])
And call it like:
python "YOURSCRIPTPATH.py" argument_1
You can have more than one command line argument:
import sys
import numpy as np
def grad(x):
# your grad function here
arr = np.array([int(sys.argv[1]), int(sys.argv[2])])
print(grad(arr))
Usage:
python gradient.py 10 5
You could just something like this in the command line:
$ python -c 'from YOURFILE import grad; print(grad(your_argument))'
I wrote some code (named exercise 2) where I define a function (named is_divisible) and it has worked perfectly.
Afterwards to learn how to import functions, I wrote the same code but without the defined function, and created a second module (named is_divisible). But whenever I import this module into the original "exercise 2" I get
No module named 'is_divisible'
I have checked that both python files are in the same folder, the name of the file is correct, and I know the code is well written because it has worked before and it is from a lecturer's of mine. I have also attempted to name the module and the function differently and to instead write:
from divis import is_divisible
but this was also unsuccessful.
Where am I going wrong? I will leave the code below:
import random
import math
import numpy as np
random_list=[]
for i in range (0,5):
r=random.randint(0,10)
random_list.append(r)
print(random_list) #five numbers from 0 to 10 are chosen and appended to a list
new_result=[print('right' for x in random_list if round(np.cosh(x)**2 - np.sinh(x)**2,2) == 1]
#checking the numbers following a maths rule
import is_divisible #trying to import the function is_divisible
divisor=3
idx = is_divisible(random_list, divisor)
for i in idx:
print(f'Value {random_list[i]} (at index {i}) is divisible by {divisor}')
the code for the function is_divisible is:
def is_divisible(x, n):
""" Find the indices of x where the element is exactly divisible by n.
Arguments:
x - list of numbers to test
n - single divisor
Returns a list of the indices of x for which the value of the element is
divisible by n (to a precision of 1e-6 in the case of floats).
Example:
>>> is_divisible([3, 1, 3.1415, 6, 7.5], 3)
[0, 3]
"""
r = []
small = 1e-6
for i, m in enumerate(x):
if m % n < small:
r.append(i)
return r
I know this question has been answered multiple times, but none of the answers seem to work for me or maybe I am not doing it correctly.
Generally, when you type import <Module> the module is the name of the file. So, if you had the function is_divisible inside a Python file named a.py, then to import it you will write from a import is_divisible. If instead, you would like to import the whole file, then you'd write import a.py, then to use the function you would use a.is_divisible(random_list, divisor).
You should also make sure that both files are in the same folder.
Let's say I have a function named "hello" in a module named a, and various other functions. Is it possible to import hello as goodbye, along with the other symbols? I am thinking of something like this, however it's not valid:
from a import hello as goodbye,*
You can import from a, then bind the new name that you want and delete the previous. Something like
from a import *
goodbye = hello
del hello
Star imports are usually not so good exactly because of namespace pollution.
from a import *
from a import hello as goodbye
from a import *
goodbye = hello
del hello
Would be another way to do it.
Next two lines work fine for me:
from core.commonActions import click_on_toolbar_tool, wait_toolbar_tool_enabled as x
from core.commonActions import wait_toolbar_tool_enabled as x, click_on_toolbar_tool
OR if you need to import all functions you can use:
from core.commonActions import *
from core.commonActions import wait_toolbar_tool_enabled as x
OR:
from core.commonActions import *
x = wait_toolbar_tool_enabled
AND if you want hello not to be more available then simply:
from core.commonActions import *
x = wait_toolbar_tool_enabled
wait_toolbar_tool_enabled = None # or del wait_toolbar_tool_enabled