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

I am just starting out with Python.
How to invoke a test script from the C: \ X \ Y \ Z directory when interactively on the command line of the Python interpreter? How to specify the full path for a file if it is not in the current working directory?

I can invoke a test script when using the Windows startup command with "python -ic: \ X \ Y \ Z \ filename.py" and it works fine. But I want to be able to call it from the Python terminal with the prompt "→>".

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

thanks

+4
source share
5

, python "escape-". Python .

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

, .

+3

REPL:

import sys
sys.path.append('c:\X\Y\Z')
import filename
+2

Exec 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())

, - ​​ ( - ), . , "-f __name__ == '__main__':", ( __name__ __main__, , script).

, Zen of Python, , :

- , ( python, , python). exec()/execfile() globals()/locals(), .

?

? script:

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

:

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

, ? , , script. . :

x = 1

script:

import very_simple_module
very_simple_module.x = 3

, :

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

, , python .

... python . ( ) sh ( PyPI):

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

. script

, : script pythonpath script:

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

, , , pythonpath, , python , script, .

, "-f __name__ == '__main__':" . :

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

, . , script sys.py, , python sys .

+1

, execfile

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

(/ , \, ('C:\\X\\Y\\Z\\filename.py') (r'C:\X\Y\Z\filename.py'))

+1

If you use IPython (and you should use it a lot more than vanilla interactive Python), you can use the magic function run(or with the prefix %:) %run:

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

See this link for more information on magic functions.

And by the way, he even has autocomplete file names.

+1
source

All Articles