Not able to properly implement import for python file - python

I am trying to import class called storePass() from test2 into test
I have done this->
test1->
import smtplib
from test2 import storePass
Gmail = storePass()
a = Gmail.returnPass()
test2->
class storePass():
Gmail_pass = "xcmsijw19021"
def returnPass(self):
return self.Gmail_pass
However I am getting the following error ->
TypeError: returnPass() takes 0 positional arguments but 1 was given
When I try to write the code as follows ->
class storePass():
Gmail_pass = "xcmsijw19021"
def returnPass(self):
return self.Gmail_pass
Gmail = storePass()
a = Gmail.returnPass()
I am getting no errors and I can execute print(a) without any problem.
So It's certainly something wrong with my import !
EDIT : Both test1 and test2 are in same directory !

I just tried to run your code and it works on my python 2.7.6 interpreter.
I print a and it gives me as a result xcmsijw19021.
This is the code I used:
file.py
import smtplib
from test2 import storePass
Gmail = storePass()
a = Gmail.returnPass()
print a
test2.py
class storePass():
Gmail_pass = "xcmsijw19021"
def returnPass(self):
return self.Gmail_pass
Then I did run python file.py and it prints me correctly the output.
I think it's some interpreter/ide problem maybe?
Python3 works aswell, by using print(a)

i tried and ran it on Ubuntu 16.04 python 2.7 and it worked as expected. make sure your two files are at the same folder or that the test2 path is in PYTHONPATH.
anyway to F.Leone python does not have a compiler and from what i know it does not depend on specific IDE.

Related

Can't import functions/modules

I'm simply trying to import a function from another script. But despite import running successfully, the functions never enter my local environment.
The paths and files look like this:
project/__main__.py
project/script_a.py
from setup import script_b
x = ABC() # NameError: name 'ABC' is not defined
print(x)
project/setup/__init__.py
project/setup/script_b.py
def ABC():
return "ABC"
I've done this before and the documentation (officials and on here) is quite straightforward but I cannot grasp what I am failing to understand. Is the function running but never entering my environment?
I also tried using...
if __name__ == '__main__':
def ABC():
return "ABC"
...as script_b.
Import the functions inside the module:
from setup.script_b import ABC
Or call the function on the modules name like said in the comments
x = script_b.ABC()

How do I execute a function from another module?

I am using python 3.6 version. I have 2 .py files as:
modbody.py
def test():
print("Statement goes here")
moduse.py
import modbody
test()
I am trying to execute moduse.py file in python interpreter using command "Python moduse.py" however, it gives me below error:
File "C:\users\Program\moduse.py", line 2, in
test() NameError: name 'test' is not defined
Please help guide me how to execute the script and call the test function here? I have also tried adding a blank init.py file to solve this but with no luck. Please not all of my files are in same directory only.
I think you meant:
import modbody
modbody.test()
Or:
from modbody import test
test()
Or:
from modbody import *
test()

Python Import Linux vs Windows

I am developping a new little project which need to run on Windows and Linux. To explain my problem I will use 3 files.
parser/__init__.py
from .toto import Parser as TotoParser
parser/toto.py
class Variable(object):
def __str__(self):
return "totoVariable"
class Parser(object):
#staticmethod
def parse(data):
return Variable()
main.py
#!/usr/bin/env python3
from parser import TotoParser
def main():
print(TotoParser.parse(""))
if __name__ == '__main__':
main()
In this project. I create several modules(file) into different packages(directory). The thing is I need to change the name of module imported. To do that I use aliasing into __init__ files.
My project run perfectly on Lunix but when I tried it on Windows this problem occurs !
ImportError: cannot import name 'TotoParser'
Sorry for my English, I am learning it...
Please rename init.py to __init__.py, I believe that it is work, case already named as __init__.py ignore this anwser...

import output of command instead of a file - python

I have a very simple script that i wish to test out.
Master script (caller.py):
#!/usr/bin/env python2.7
import test2
test2.printMe()
Function/Module Script (test2.py):
def printMe():
print 'this actually works'
When I run caller.py, it works. Because the test2.py script exists in the same directory from which I'm calling caller.py.
What happens if i need to make the function(s) defined in test2.py available to the caller.py script, through a variable? There are times when the content of the test2.py function script wont always be in a file. Sometimes, it's inside a variable.
So basically, im looking for a way to access the functions that are in a variable just as import would access functions that are in a file.
I wish to be able to do something like this:
from commands import *
def run_command(cmd):
status, text = getstatusoutput(cmd)
print text
run_command('python /tmp/test2.py')
test2.printMe()
Please advise.
Try this:
from sys import path as sys_path
from os import path
def import_module(path_to_py_file):
dir_name, module_name = path.split(path.splitext(path_to_py_file)[0])
sys_path.append(dir_name)
return __import__(module_name)
Now you can do this:
test2 = import_module(r'/tmp/test2.py')
test2.printMe()

How can I call another python script, in a python script, based on a variable in a config file?

I have below py script to download the files from artifactory.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import tarfile
import urllib
from urllib import urlretrieve
import ConfigParser
Config = ConfigParser.ConfigParser()
Config.read('/vivek/release.conf')
code_version = Config.get('main', 'app_version')
os.chdir('/tmp/')
arti_st_url='http://repo.com/artifactory/libs-release- local/com/name/tgz/abc.ear/{0}/abc.ear-{0}.tar.gz'.format(code_version)
arti_st_name='abc.ear-{0}.tar.gz'.format(code_version)
arti_sl_url='http://repo.com/artifactory/libs-release- local/com/name/tgz/def.ear/{0}/def.ear-{0}.tar.gz'.format(code_version)
arti_sl_name='def.ear-{0}.tar.gz'.format(code_version)
urllib.urlretrieve(arti_st_url, arti_st_name)
urllib.urlretrieve(arti_sl_url, arti_sl_name)
oneEAR = 'abc.ear-{0}.tar.gz'.format(code_version)
twoEAR = 'def.ear-{0}.tar.gz'.format(code_version)
tar = tarfile.open(oneEAR)
tar.extractall()
tar.close()
tar1 = tarfile.open(twoEAR)
tar1.extractall()
tar1.close()
os.remove(oneEAR)
os.remove(twoEAR)
This script works perfectly, thanks to stackoverflow.
Here's the next question. There's a variable "protocol" in release.conf. If it's equal to "localcopy", there's an existing py script that does something. If the "protocol" is equal to "artifactory",
above script should be called and executed. How can I achieve it?
Note: I am a beginner in Python, but my tasks are not. So, please help me out guys.
You could simply use:
import os
os.system("script_path")
to execute the script file. But there should be a line called shebang in the very top of that script file, you want to execute. If your python interpreter would be in /usr/bin/python this would be:
#!/usr/bin/python
Assuming you are a Linux user.
In Windows shebang isn't supported. It determines what program to use running *.py file itself.
//Edit:
To call that two scripts depending on a property config value you could just make another script called for example runthis.py which contains instruction like:
protocol = Config.get('main', 'protocol')
if protocol == 'localcopy':
os.system('path_to_localcopy_script)
if protocol == 'antifactory':
os.system('path_to_other_script')
Dont forgot to import needed modules in that new script.
Then you just run script you just made.
That is one way to do this.
If you dont want to create additional script, then put that code you wrote in a function, like:
def main():
...
Your code
...
And on the very bottom of your script file write:
if __name__ = '__main__':
protocol = Config.get('main', 'app_version')
if protocol == 'localcopy':
main()
if protocol == 'antifactory':
os.system('path_to_other_script')
if __name__ = '__main__' would execute only if you run that script by yourself (not by call from an other sctipt for example)

Categories

Resources