Sovith Kothari
Sovith Kothari

Reputation: 3

Python inputs from another python file

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.

Upvotes: 0

Views: 257

Answers (2)

firelynx
firelynx

Reputation: 32214

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

Upvotes: 0

Mukul
Mukul

Reputation: 880

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.

Upvotes: 0

Related Questions