[GIS] Calling the Python file from the QGIS Python console

pythonqgisqgis-python-console

Situation: I have a Python file called 'Hello.py' and another Python file called 'File1.py'. Hello.py imports File1.py.

Hello.py code is:

print 'hello people'
import File1
File1

File1.py code is:

print 'hello world'

The files are located:

My files is located C:\Program Files\QGIS 2.18\PyPack\

Using 'OSGeo4W.bat' provided in the QGIS directory, I execute the following commands:

C:\Program Files\QGIS 2.18>cd C:\Program Files\QGIS 2.18\PyPack

python Hello.py

And the output is:

hello people
hello world

What do I type in this window to run Hello.py, which gives the output?
enter image description here

I have tried:

1 – dragging the 'Hello.py' file into the QGIS Python console

2 – the following command:

execfile(u'C:\Program Files\QGIS 2.18\PyPack\Hello.py'.encode('mbcs'))

3 – I tried to open 'Hello.py' in the QGIS python editor and run it with the same output.

enter image description here

And the outputs were:

hello people 
Traceback (most recent call last): 
File "<input>", line 1, in <module> 
File "C:\Program Files\QGIS 2.18\PyPack\Hello.py", line 2, in <module> 
import File1 
File "C:/PROGRA~1/QGIS2~1.18/apps/qgis/./python\qgis\utils.py", line 607, in _import 
mod = _builtin_import(name, globals, locals, fromlist, level) 
ImportError: No module named File1 

Best Answer

1) Just drag the python file to frame of python in QGIS.
2) Another way:

execfile(u'C:/hi.py'.encode('mbcs'))

To import python modules while working on QGIS, write below lines:

import sys 
sys.path 
sys.path.append("C:/PyPack") #Add this folder to python environment path
import File1 
Related Question