global name 'json' is not defined - python

Here is the beginning of createPeliMelo.py
def creation(path,session):
myPathFile=path+session+'.txt'
print myPathFile
pelimeloFile = open(path+session+'.txt', 'r')
with pelimeloFile as inf:
data = json.loads(inf.read())
Here is my Python script inside Maya:
import maya.cmds as cmds
import json
import os
from itertools import islice
import createPeliMelo as PeliMelo
PeliMelo.creation('C:/Users/francesco/Desktop/pelimelo video printemps/','session5723')
Here is the error I got:
Error: line 1: NameError: file C:/Users/francesco/Documents/maya/2016/scripts\createPeliMelo.py line
17: global name 'json' is not defined #
Line 17 is: data = json.loads(inf.read())
Where am I wrong?

When you import something, that import only applies to the file that you imported it in. This means that if you want to use json in createPeliMelo.py you need to do import json in THAT file, not your second script. Imports from one file will not propagate over to another.

Related

Getting code from a .txt on a website and pasting it in a tempfile PYTHON

I was trying to make a script that gets a .txt from a websites, pastes the code into a python executable temp file but its not working. Here is the code:
from urllib.request import urlopen as urlopen
import os
import subprocess
import os
import tempfile
filename = urlopen("https://randomsiteeeee.000webhostapp.com/script.txt")
temp = open(filename)
temp.close()
# Clean up the temporary file yourself
os.remove(filename)
temp = tempfile.TemporaryFile()
temp.close()
If you know a fix to this please let me know. The error is :
File "test.py", line 9, in <module>
temp = open(filename)
TypeError: expected str, bytes or os.PathLike object, not HTTPResponse
I tried everything such as a request to the url and pasting it but didnt work as well. I tried the code that i pasted here and didnt work as well.
And as i said, i was expecting it getting the code from the .txt from the website, and making it a temp executable python script
you are missing a read:
from urllib.request import urlopen as urlopen
import os
import subprocess
import os
import tempfile
filename = urlopen("https://randomsiteeeee.000webhostapp.com/script.txt").read() # <-- here
temp = open(filename)
temp.close()
# Clean up the temporary file yourself
os.remove(filename)
temp = tempfile.TemporaryFile()
temp.close()
But if the script.txt contains the script and not the filename, you need to create a temporary file and write the content:
from urllib.request import urlopen as urlopen
import os
import subprocess
import os
import tempfile
content = urlopen("https://randomsiteeeee.000webhostapp.com/script.txt").read() #
with tempfile.TemporaryFile() as fp:
name = fp.name
fp.write(content)
If you want to execute the code you fetch from the url, you may also use exec or eval instead of writing a new script file.
eval and exec are EVIL, they should only be used if you 100% trust the input and there is no other way!
EDIT: How do i use exec?
Using exec, you could do something like this (also, I use requests instead of urllib here. If you prefer urllib, you can do this too):
import requests
exec(requests.get("https://randomsiteeeee.000webhostapp.com/script.txt").text)
Your trying to open a file that is named "the content of a website".
filename = "path/to/my/output/file.txt"
httpresponse = urlopen("https://randomsiteeeee.000webhostapp.com/script.txt").read()
temp = open(filename)
temp.write(httpresponse)
temp.close()
Is probably more like what you are intending

ImportError: cannot import name 'Random' in pycharm

I write a simple python in pycharm:
import requests
req = requests.get("http://phika.ir/")
print(req)
req = requests.get("https://phika.ir/python")
print(req)
but in result I came up with:
random
from random import Random as _Random
ImportError: cannot import name 'Random'
as you see, I didn't use random function!
I found the problem!!! I have saved a python file named random.py in current directory. so, I changed the name of this file and the problem solved.

How can I call a variable from another file?

I have two files. The first file, we'll call it "Main.py". The second, "file1.py".
I want to be call a variable from Main.py and write the value to a new file called "tempFile.txt". I've tried importing "Main.py" but I get an Attritbute error.
Here's an example of "File1.py"
import os
import sys
import main
# This function should write the values from Main.py to a tempFile
# and reads the contents to store into a list.
def writeValues():
tempFile = open('tempFile.txt', 'w+')
tempFile.write(str(X_Value))
tempFile.write("\n")
tempFile.write(str(Y_Value))
zoneValues = [line.rstrip('\n') for line in open('tempFile.txt')]
print zoneValues
# X_Value and Y_Value are the variables in Main.py I am trying to access
def readZoneValues(): # Creates a list from values in tempFile.txt
valuesList = [line.rstrip('\n') for line in open('tempFile.txt')]
print valuesList
I've tried other looking for answers but there was no clear answer to this specific issue.
EDIT:
Main.py
import os
import sys
import file1
X_Value = 1000
Y_Value = 1000
# For statement that manipulates the values, too long to post.
for "something":
if "something":
# after the values are calculated, kick it to the console
print "X Value: " + str(X_Value) + "\n"
print "Y Value: " + str(Y_Value) + "\n"
I need the values of the variables to be written to the tempFile after Main.py has been processed.
EDIT:
I have tried having the tempFile created in Main.py, but for some reason my function for reading the tempFile and adding the values to a list do not appear, however, the values DO APPEAR after I delete the tempFile creation in Main.py and uncomment the write function in File1.py
The code you're presenting creates a circular import; i.e. main.py imports file1.py and file1.py imports main.py. That doesn't work. I would recommend changing write_values() to accept two parameters, and then passing them in from main.py, and eliminating the import of main into file1:
main.py:
import os
import sys
import file1
X_Value = 1000
Y_Value = 1000
file1.writeValues(X_Value, Y_Value)
file1.py:
import os
import sys
# This function should write the values from Main.py to a tempFile
# and reads the contents to store into a list.
def writeValues(X_Value, Y_Value):
tempFile = open('tempFile.txt', 'w+')
tempFile.write(str(X_Value))
tempFile.write("\n")
tempFile.write(str(Y_Value))
tempFile.close()
zoneValues = [line.rstrip('\n') for line in open('tempBeds.txt')]
print zoneValues
def readZoneValues(): # Creates a list from values in tempFile.txt
valuesList = [line.rstrip('\n') for line in open('tempFile.txt')]
print valuesList
Try importing it.
from YourFileName import *
Also, when calling,
YourFileName.tempFile
If you want to call only your variable then,
from YourFileName import VarName1

How can I make python script(X) reload dynamically changing variables in another module(Y) and then re-import updated module(Y) in same script(X)?

I'm new to Python, I'm stuck with a code. I have tried my best to show my problem with below sample code. I'm playing with 4 files.
This is the runme file. That I'm running.
command > python runme.py
import os
with open("schooldata.txt", "r") as filestream: #opening schooldata.txt file
for line in filestream:
currentline = line.split(",")
a = currentline[0]
b = currentline[1]
c = currentline[2]
#creating a school_info.py file with value of a,b,c that are further imported by mainfile.py
f = open('school_info.py','w')
f.write("a= \"" + currentline[1] + "\"\n")
f.write("b= \"" + currentline[2] + "\"\n")
f.write("c= \"" + currentline[3] + "\"\n")
f.close()
#importing mainfile.py and calling its functions.
from mainfile import give_to_student
give_to_student("Rickon")
from mainfile import give_to_teacher
give_to_student("Carolina")
Second file is schooldata.txt from where I want to read the value of a,b,c. This is our main school data file from which we take authorization data. I'm reading line by line from this file and creating a,b,c by splitting it with (,).
12313,mshd1732,2718230efd,
fhwfw,382842324,238423049234230,
fesj32,282342rnfewk,43094309432,
fskkfns,48r209420fjwkfwk,2932042fsdfs,
38234290,fsfjskfjsdf,2942094929423,
Third file is school_info.py which I'm creating with this data everytime. This file is created everytime when a line is read from schooldata.txt file. So fresh file everytime with fresh and unique data of a,b,c.
a = "asb12"
b = "121002"
c = "mya122344"
Now here comes the mainfile.py which is having functions like give_to_student and give_to_teacher. This file is importing data from school_info.py, so as to create authorization code using values of a,b,c.
and function definition of give_to_student and give_to_teacher which uses these function definitions.
import os
import schoollib #(internal school lib)
#importing School_info.py file so as to get value of a,b,c
from school_info import *
#It creates authorisation code internally
lock = auth(a,b,c,d)
#This authorisation code is used to call internal function
def give_to_student():
lock.give(student)
def give_to_teacher():
lock.give(teacher)
So now let me share the exact problem that I'm facing as of now, I'm unable to get authorization code loaded for mainfile.py everytime it is imported in runme.py file. When I'm calling runme.py file it is giving same authorization code to all users every time.
It is not able to use authorization code that is create after reading second line of schooldata.txt
With mainfile.py file If I'm trying to reload module using. import importlib and then importlib.reload(mainfile.py) in runme.py.
#Added it in runme.py file
import importlib
importlib.reload(mainfile)
It is still giving authorization for first line of data(schooldata.txt).
Similar thing I tried in mainfile.py.
I tried to import importlib and then importlib.reload(school_info).
#added it in mainfile.py
import importlib
importlib.reload(school_info)
importlib.reload(school_info)
NameError: name 'school_info' is not defined
But it giving error, that school_info module doesn't exist.
Please throw some light on it, and how can I make it work.
P.S. I'm using python 3.5. Thanks
Why don't you try to combine the school_info.py and mainfile.py.
If you can run a combined loop.
import os
import schoollib #(internal school lib)
with open("schooldata.txt", "r") as filestream: #opening schooldata.txt file
for line in filestream:
currentline = line.split(",")
a = currentline[0]
b = currentline[1]
c = currentline[2]
#It creates authorisation code internally
lock = auth(a,b,c,d)
#This authorisation code is used to call internal function
def give_to_student():
lock.give(student)
def give_to_teacher():
lock.give(teacher)
#function calling
give_to_student("Rickon")
give_to_student("Carolina")
I hope this solves your purpose.

Error when opening txt file in Python

I have to work with a txt file and to do that I used the following code:
inputFile = open("C:/Abaqus_JOBS/Job-M1-3_4.inp", "r") #CAE INPUT FILE
However I get this error when I ran this line in a specific application for running python scripts available in another program. I don't get any error when I ran it in Spyder.
TypeError: an integer is required
I don't have a clue why this error occurs....
EDIT:
lines of code until line in question
import os
from os import *
from abaqus import *
from odbAccess import *
from abaqusConstants import *
import time
import itertools
os.chdir('C:\\Abaqus_JOBS')
LCKf = 'C:\\Abaqus_JOBS\\Job-M1-3_2.lck'
STAf = 'C:\\Abaqus_JOBS\\Job-M1-3_2.sta'
def get_num_part(s):
for i in xrange(len(s)):
if s[i:].isdigit():
return s[i:]
return ''
if not path.exists(LCKf):
time.sleep(1)
while path.exists(LCKf) and path.isfile(LCKf) and access(LCKf, R_OK):
variableX = 0
else:
odb = openOdb(path='Job-M1-3_2.odb')
#get CF
#session.odbs[name].steps[name].frames[i].FieldOutput
myAssembly = odb.rootAssembly
myAssemblyName = odb.rootAssembly.name
nsteps=len(odb.steps.values())
step1 = odb.steps.values()[nsteps-1]
step1Name = odb.steps.values()[nsteps-1].name
myInstanceName = odb.rootAssembly.instances.values()[0].name
dCF3=[]
dCF3v=[]
coordFv=[]
fileData = [] #array with the input file
nodes = [] #array with the content of *NODES
inputFile = open("C:/Abaqus_JOBS/Job-M1-3_4.inp", "r") #CAE INPUT FILE
#fileData = variable with all the lines of the inp file
for line in inputFile:
fileData.append([x.strip() for x in line.split(',')])
the error is:
Traceback (most recent call last):
File "c:/Abaqus_JOBS/results.py", line 47, in <module>
inputFile = open("C:/Abaqus_JOBS/Job-M1-3_4.inp", "r") #CAE INPUT FILE
TypeError: an integer is required
With the
from os import *
You're importing all os stuff in the global namespace, including os.open(). Don't do this.
The second argument, flags, is defined as integer constants while you're providing a single-character string r. This is basically what DSM was telling you and what Lattyware said.
open() included in Python by default in the global namespace, which you were expecting apparently, is different:
Note: This function is intended for low-level I/O. For normal usage,
use the built-in function open(), which returns a “file object” with
read() and write() methods (and many more). To wrap a file descriptor
in a “file object”, use fdopen().

Categories

Resources