简体   繁体   English

无法从源目录外部运行 python 文件

[英]Cannot run python file from outside of source directory

I am trying to run a python file at C:\Users\maxwe\PATH TO FILE\testScripts\writeToFile.py from outside of the testScripts folder.我正在尝试从 testScripts 文件夹之外的 C:\Users\maxwe\PATH TO FILE\testScripts\writeToFile.py 运行 python 文件。

Notice the below command prompt screen shot (I included the version to show that the python command is resolving to something).请注意下面的命令提示屏幕截图(我包含的版本显示python命令正在解析某些内容)。 The writeToFile.py script seems to execute since I receive no errors but it does not write Hello World to the file like I want it to. writeToFile.py 脚本似乎执行了,因为我没有收到任何错误,但它没有像我想要的那样将 Hello World 写入文件。

I can run the script from within the testScripts folder and it works as expected but the end goal with this project is to run the python script from a Java Spring API that will reside outside that source folder by running something like Runtime.getRuntime().exec("python C:\Users\maxwe\PATH TO FILE\testScripts\writeToFile.py"); I can run the script from within the testScripts folder and it works as expected but the end goal with this project is to run the python script from a Java Spring API that will reside outside that source folder by running something like Runtime.getRuntime(). exec("python C:\Users\maxwe\PATH TO FILE\testScripts\writeToFile.py"); so "cd"ing into the folder and running the script doesn't help much.所以“cd”进入文件夹并运行脚本并没有多大帮助。

Thanks in advance!提前致谢!

命令提示符屏幕截图

Here is the python file as well:这里也是 python 文件:

# -*- coding: utf-8 -*-
"""
Created on Feb 25 2021

@author: maxwe
"""
def run():
    file1 = open("log.txt","w")

    file1.write("Hello World")
    file1.close() 

run()

There are more "pythonic" ways of doing this using os and redefining your directory.使用 os 和重新定义目录有更多“pythonic”方法。 But for simplicity and to directly answer your question you need to define the absolute path where this file can be found.但为了简单起见并直接回答您的问题,您需要定义可以找到此文件的绝对路径。

  path = 'C:\\Users\\maxwe\\Desktop\\personal_projects\\water_robot\\log.txt'
    
    with open(path, 'w') as f:
        f.write('Hello World')
        f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM