简体   繁体   English

如何使用Atom编辑器在Python中将脚本的路径设置为工作目录?

[英]How can I set the path of the script as working directory in Python using Atom editor?

I want to set the path of the python script as the working directory. 我想将python脚本的路径设置为工作目录。 I've tried the solutions I've found other solutions, but they aren't working for me. 我尝试过的解决方案找到了其他解决方案,但它们对我不起作用。

This solution: 此解决方案:

import os

path = os.path.dirname(os.path.realpath(sys.argv[0]))
dn = os.path.dirname(os.path.realpath("__file__"))
dn

gives: 给出:

'C:\\Users\\23392\\Desktop'

and my script is in a folder of desktop. 我的脚本在桌面文件夹中。

This solution: 此解决方案:

import os
print(os.path.dirname(os.path.realpath(__file__)))

gives the following error: 给出以下错误:

NameError: name '__file__' is not defined

I need to define it as a string to prevent the error. 我需要将其定义为字符串以防止错误。 And I get the same result that the previous one: 我得到的结果与上一个相同:

'C:\\Users\\23392\\Desktop'

The path should be: 路径应为:

C:\Users\23392\Desktop\05_Work\test.py

EDIT 编辑

I've found a partial solution. 我找到了部分解决方案。 If I open the file with right click->open with->Atom, it recognizes the path of the file. 如果我右键单击->打开方式-> Atom打开文件,它将识别文件的路径。 It works this way but it has to be another way to do it. 它以这种方式工作,但必须是另一种方式。

Please try this version: 请尝试以下版本:

import os

abspath = os.path.abspath(__file__)
basename = os.path.basename(__file__)
fullpath = os.path.join(abspath + "\\" + basename)

print(fullpath)

Write this code into a file and then run it using Python interpreter. 将此代码写入文件,然后使用Python解释器运行它。

If you try it from an interactive shell it will not work, __file__ is not defined in the interactive interpreter because it is meaningless there. 如果您从交互式外壳程序中尝试它将不起作用,则在交互式解释器中未定义__file__,因为在那里它没有意义。

It is set by the import implementation, so if you use a non-standard import mechanism it might also be unset. 它是由导入实现设置的,因此,如果您使用非标准的导入机制,则可能也未设置它。

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

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