I have a python file(file1.py) where i have written a script. Now, my friend asked me to keep the inputs in another python file(file2.py) and import the file in file1.py so that its becomes easy to modify the inputs if we keep it seperate file. So i created file2.py, copied the inputs there and saved it. Then i wrote the following line in file1.py: from file2 import * but its throwing error:
TASK [Run the python script]
********************************************************************************************************************************************************************************************************************************* fatal: [automation_server]: FAILED! => {"changed": true, "msg":
"non-zero return code", "rc": 1, "stderr": "Shared connection to
10.242.174.192 closed.\r\n", "stderr_lines": ["Shared connection to 10.242.174.192 closed."], "stdout": "/etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such
file or directory\r\nTraceback (most recent call last):\r\n File
\"/home/bgnanasekaran/.ansible/tmp/ansible-tmp-1591957555.760499-407
182191177023663/download_RI_build.py\", line 8, in \r\n
from file2 import
*\r\nModuleNotFoundError: No module named 'file2'\r\n", "stdout_lines": ["/etc/profile.d/lang.sh: line 19: warning: setlocale:
LC_CTYPE: cannot change locale (UTF-8): No such file or directory",
"Traceback (most recent call last):", " File
\"/home/bgnanasekaran/.ansible/tmp/ansible-tmp-1591957555.760499-407
182191177023663/download_RI_build.py\", line 8, in ", "
from file2 import *", "ModuleNotFoundError: No module named 'file2'"]}
Note: I'll give some example of inputs in file2.py -
name="Suresh"
college="VIT"
Also note: I wrote all these python scripts to make it run with ansible playbook. This script is a part of play in my ansible playbook.
Please help me do this. I want a python file where i can store my python script inputs and use the same file in python script. This is not so related to ansible but more related to python.
you need a configuration file this post might help you or you can create a class and all required variable as a class variable and import the class into your script.
import is for python files only.
If you want to read content of a file you need to open it.
with open('filename', 'r') as handler:
print(handler.readlines())
Is a minimal example
You could also try to use environment varibales, which is a much more common practice when dealing with deployment strategies
import os
VARIABLE = os.getenv('VARIBALE', 'default_value')
Then you run the script with:
VARIABLE=this ./pythonscript.py
Or export the variable into the environment in another way
Related
Trying to call a function yamlCreation() which is in another directory into this python file ..
the path of this file is
path:bss_micro_svcs/bss_micro_svcs/kubectl.py
Calling File: "kubectl.py"
from bss_micro_svcs.kubectl_utils.templating_to_yaml import yamlCreation
class Kube(Svcs):
def startService(self, cluster_info, service, service_profile):
yamlCreation()
k=Kube()
k.startService()
yamlCreation() function is in this python file named "templating_to_yaml.py"
the path of the file is..
path:bss_micro_svcs/kubectl_utils/templating_to_yaml.py
function to be called is inside this file:"templating_to_yaml.py"
file_loader = FileSystemLoader('bss_micro_svcs/bss_micro_svcs/yamls/templates')
env = Environment(loader=file_loader)
#deployment.yaml templating
deployment_template=env.get_template('deployment.tmpl')
deployment_output=deployment_template.render(deployment_name='nginx-deployment',deployment_app='nginx',deployment_replicas='3',deployment_container_name='nginx',deployment_image='nginx:1.14.2',deployment_container_port=80)
deployment_outfile=open('bss_micro_svcs/bss_micro_svcs/yamls/services/integration/deployment.yaml','w')
deployment_outfile.write(deployment_output)
deployment_outfile.close()
#*********************************************************************************************************************************************************#
#service.yaml templating
service_template=env.get_template('services.tmpl')
service_output=service_template.render(service_name='integration-service',service_name_space='demo-sandbox',service_app='integration',service_port=8090,target_port=8090)
service_outfile=open('bss_micro_svcs/bss_micro_svcs/yamls/services/integration/services.yaml','w')
service_outfile.write(service_output)
service_outfile.close()
GETTING AN ERROR:
┌──(bss_micro_svcs-jnO67Li7)(RK㉿kali)-[~/Desktop/servicelaunchmgr]
└─$ /home/RK/.local/share/virtualenvs/bss_micro_svcs-jnO67Li7/bin/python /home/RK/Desktop/servicelaunchmgr/bss_micro_svcs/bss_micro_svcs/kubectl.py
Traceback (most recent call last):
File "/home/RK/Desktop/servicelaunchmgr/bss_micro_svcs/bss_micro_svcs/kubectl.py", line 2, in <module>
from bss_micro_svcs.kubectl_utils.templating_to_yaml import yamlCreation
ModuleNotFoundError: No module named 'bss_micro_svcs'
You could set environment variable PYTHONPATH so the interpreter could know where to start looking for the module to import. I would suggest to set it in the root module.
Reference: https://bic-berkeley.github.io/psych-214-fall-2016/using_pythonpath.html
I have a script, let's call it /home/pi/somescript.py and when I call it with /bin/python3.7 /home/pi/somescript.py everything works as it should.
Now I'm trying to call from a php script with exec('/bin/python3.7 /home/pi/somescript.py', $output, $ret_code);. This however throws a ModuleNotFoundError.
But when I run the interactive PHP shell and paste the above exec in there, it also works. Am I missing something? What could be the cause of this? How do I fix this?
The relevant part of the python script:
import sys
sys.stderr = sys.stdout # so I get the stacktrace in the $output of the php file
from iso3166 import countries # <- error here
# ...
I'm running a lighttpd server. The PHP file lies in /var/www/html/info.php and I access it via a browser with http://raspberrypi:8080/info.php
The relevant part of the PHP file:
exec('/bin/python3.7 /home/pi/somescript.py', $output, $ret_code);
$data = ["out" => $output];
header('Content-Type: application/json');
echo json_encode($data);
// this way I get the output when in the browser
The stacktrace I get:
Traceback (most recent call last):
File "/home/pi/somescript.py", line 6, in <module>
from iso3166 import countries
ModuleNotFoundError: No module named 'iso3166'
I am learning python and I am trying to do a simple task of reading information from a config file.
So using the Python Doc and this similar problem as a reference I created two files.
This is my config file config.ini (also tried config.cfg)
[DEFAULT]
OutDir = path_to_file/
[AUTH]
TestInt = 100
TestStr = blue
TestParse = blua
and this is my python file test.py
import ConfigParser
from ConfigParser import *
config = ConfigParser()
config.read(config.cfg)
for name in config.options('AUTH'):
print name
out = config.get('DEFAULT', 'OutDir')
print 'Output directory is ' + out
however when running the command python test.py I am erroring out and receiving this error
Traceback (most recent call last):
File "test.py", line 7, in <module>
config.read(config.cfg)
AttributeError: ConfigParser instance has no attribute 'cfg'
Note: I thought that meant it the extension couldn't be read so I created the .ini file and changed it in the code and I received the same error but it instead read ...has no attribute 'ini'
I am not sure what I am doing wrong since I am doing the exact same as the python doc and the solution someone used to fix this similar issue.
config.read takes a string as its argument. You forgot to quote the file name, and config was coincidentally the name of a Python object (the module) that potentially could have a cfg attribute. You'd get an entirely different error if you had written config.read(foobarbaz.ini).
The correct line is
config.read('config.cfg') # or 'config.ini', if that's the file name
I am working on creating a WebGL interface for which I am trying to convert FBX models to JSON file format in an automated process using python file, convert_fbx_three.py (from Mr. Doob's GitHub project) from command line.
When I try the following command to convert the FBX:
python convert_fbx_three.py Dolpine.fbx Dolpine
I get following errors:
Error in cmd:
Traceback (most recent call last):
File "convert_fbx_three.py", line 1625, in <module>
sdkManager, scene = InitializeSdkObjects()
File "D:\xampp\htdocs\upload\user\fbx\FbxCommon.py", line 7, in InitializeSdkObjects
lSdkManager = KFbxSdkManager.Create()
NameError: global name 'FbxManager' is not defined
I am using Autodesk FBX SDK 2012.2 available here on Windows 7.
Can you please try the following:
import FbxCommon
.
.
.
lSdkManager, lScene = FbxCommon.InitializeSdkObjects()
You probably need to add environment variables pointing to the folder that contains fbx.pyd, FbxCommon.py, and fbxsip.pyd prior to calling anything in those modules.
I am trying to setup a program where when someone enters a command it will run that command which is a script in a sub folder called "lib".
Here is my code:
import os
while 1:
cmd = input(' >: ')
for file in os.listdir('lib'):
if file.endswith('.py'):
try:
os.system(str(cmd + '.py'))
except FileNotFoundError:
print('Command Not Found.')
I have a file: lib/new_user.py But when I try to run it I get this error:
Traceback (most recent call last):
File "C:/Users/Daniel/Desktop/Wasm/Exec.py", line 8, in <module>
exec(str(cmd + '.py'))
File "<string>", line 1, in <module>
NameError: name 'new_user' is not defined
Does anyone know a way around this? I would prefer if the script would be able to be executed under the same window so it doesn't open a completely new one up to run the code there. This may be a really Noob question but I have not been able to find anything on this.
Thanks,
Daniel Alexander
os.system(os.path.join('lib', cmd + '.py'))
You're invoking new_user.py but it is not in the current directory. You need to construct lib/new_user.py.
(I'm not sure what any of this has to do with windows.)
However, a better approach for executing Python code from Python is making them into modules and using import:
import importlib
cmd_module = importlib.import_module(cmd, 'lib')
cmd_module.execute()
(Assuming you have a function execute defined in lib/new_user.py)