FAQ
2023-02-18 15:31:07 时间
常见问题
本节列出常见的一些问题。
如何获取当前路径
当前路径可以用'.'
表示,再用os.path.abspath()
将其转换为绝对路径:
# -*- coding:utf-8 -*-
# test.py
import os
print(os.path.abspath('.'))
运行结果:
$ python3 test.py
/Users/michael/workspace/testing
如何获取当前模块的文件名
可以通过特殊变量__file__
获取:
# -*- coding:utf-8 -*-
# test.py
print(__file__)
输出:
$ python3 test.py
test.py
如何获取命令行参数
可以通过sys
模块的argv
获取:
# -*- coding:utf-8 -*-
# test.py
import sys
print(sys.argv)
输出:
$ python3 test.py -a -s "Hello world"
['test.py', '-a', '-s', 'Hello world']
argv
的第一个元素永远是命令行执行的.py
文件名。
如何获取当前Python命令的可执行文件路径
sys
模块的executable
变量就是Python命令可执行文件的路径:
# -*- coding:utf-8 -*-
# test.py
import sys
print(sys.executable)
在Mac下的结果:
$ python3 test.py
/usr/local/opt/python3/bin/python3.4
相关文章
- 彻底搞懂Python pip
- Python3.11正式版,它来了!
- Python猜数字小游戏
- 你真的会整理文件吗(FindDupFile去重+Python批量重命名)
- 优雅整理Python中的import
- python的环境,你再也不用愁
- Python下Tesseract Ocr引擎及安装介绍
- Python 操作Excel-openpyxl模块使用
- Python-数据的多种存储形式
- python3 http.server模块 搭建简易 http 服务器
- Python爬虫-scrapyd框架部署
- Python爬虫-Scrapy-Redis分布式
- Python 爬虫-feapder 框架简介
- Python BeautifulSoup简介
- Python 协程 asyncio 极简入门与爬虫实战
- Python协程-gevent
- Python协程-greenlet
- Python协程-yield
- Python爬虫解析利器PyQuery详解
- python 元类