Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a .py script from a specific file path in Python interpreter

Tags:

python

I am just getting started with Python.
How do I call a test script from C:\X\Y\Z directory when in Python interpreter command line in interactive mode? How do I specify the full path for the file when it is not in the current working directory?

I can call a test script when using the windows run command with "python -i c:\X\Y\Z\filename.py" and it runs fine. But I want to be able to call it form the Python terminal with the ">>>" prompt.

(I searched and searched for two hours and could not find an answer to this, although it seems like it should be a common question for a beginner and an easy thing to do.)

Thanks

like image 466
BioData41 Avatar asked Feb 22 '14 19:02

BioData41


People also ask

How do I run a Python script from the path?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!

How do I call a Python script from another file?

Use the execfile() Method to Run a Python Script in Another Python Script. The execfile() function executes the desired file in the interpreter. This function only works in Python 2. In Python 3, the execfile() function was removed, but the same thing can be achieved in Python 3 using the exec() method.


5 Answers

Since you are using backslashes for the file path, python interprets those as "escape characters." When writing the file path in Python, make sure to use forward slashes.

with open("C:/X/Y/Z/filename.py", "r") as file:
    exec(file.read())

Double backslashes also work, but I prefer the cleaner look of forward slashes.

like image 178
camleng Avatar answered Oct 25 '22 05:10

camleng


If you want to import it into the REPL:

import sys
sys.path.append('c:\X\Y\Z')
import filename
like image 43
slezica Avatar answered Oct 25 '22 05:10

slezica


If you want to execute code from a file within the interpreter, you can use execfile

execfile('C:/X/Y/Z/filename.py')

(/ works as path separator in all operating systems, if you use \, you need to escape them ('C:\\X\\Y\\Z\\filename.py')or use raw string literal (r'C:\X\Y\Z\filename.py'))

like image 32
Imran Avatar answered Oct 25 '22 04:10

Imran


If you are using IPython (and you should use, it's much more useful than vanilla interactive Python), you can use magic function run (or with % prefix: %run):

run C:\\X\\Y\\Z\\filename.py
%run C:\\X\\Y\\Z\\filename.py

See this link for more information about magic functions.

And by the way, it has even auto completion of filenames.

like image 22
Stan Prokop Avatar answered Oct 25 '22 06:10

Stan Prokop


Exec the heck out of it

Python 2.x:

execfile("C:\\X\Y\\Z")

Python 3+:

with open("C:\\X\Y\\Z", "r") as f:
    exec(f.read())

Still, that is very bad practice - it executes code from a string (at some point), instead of using preferred and safer way of importing modules. Still, when you import module and have some of its code after "-f __name__ == '__main__':", that parts won't work (because __name__ in imported module won't be __main__, and it would be, if you ran it as single script).

It is bad for many reasons, in some sense strongly connected to Zen of Python, but if you're beginner, this should speak to you:

When you do anything in interactive mode, you work on some namespace (this term is very important for understanding python, if you don't know it, check it in python language reference). When you exec()/execfile() something without providing globals()/locals(), you may end up with modified namespace.

Modified namespace?

What does it mean? Lets have a script like that:

radius = 3
def field_of_circle(r):
    return r*r*3.14
print(field_of_circle(radius))

Now, you have following session:

>>>radius = 5
>>>execfile("script_above.py")
28.26
>>>print(radius)
3

You see what happens? Variables defined by you in interactive session will get overwritten by values from end of script. The same goes for modifying already imported external modules. Lets have a very simple module:

x = 1

and executed script:

import very_simple_module
very_simple_module.x = 3

Now, here's a interpreter interactive session:

>>>import very_simple_module
>>>print(very_simple_module.x)
1
>>>execfile("executed_script.py")
>>>print(very_simple_module.x)
3

Run another interpreter

Interactive sessions are very useful for many things, but not for many things, but running python scripts is not one of them.

Unless... you wanna play tough and use python shell as system shell. Then, you can use subprocess (in standard library) or sh (which can be found on PyPI):

>>>import subprocess
>>>subprocess.call(["python", "C:\\X\Y\\Z"], shell=True)
>>>from sh import python
>>>python("C:\\X\Y\\Z")

Those won't have this problem with modifying interactive interpreters namespace

See script as module

Also, there is one more option: in interactive session add directory with script to pythonpath, and import module named as script:

>>>import sys
>>>if "C:\\X\\Y" not in sys.path:
    sys.path.append("C:\\X\\Y")
>>>import Z

Remember that directory in which interpreter was started is automatically on pythonpath, so if you've ran python in the same directory as your script, you just have to use 3rd of lines above.

Interpreters namespace won't change, but code after "-f __name__ == '__main__':" won't be executed. Still you can access scripts variables:

>>>radius = 5
>>>import first_example_script
>>>print(radius)
5
>>>print(first_example_script.radius)
3

Also, you can have module name conflict. For example, if your script was sys.py, then this solution will work, because python will import builtin sys module before yours.

like image 26
Filip Malczak Avatar answered Oct 25 '22 04:10

Filip Malczak