繁体   English   中英

python 脚本可以将自己的内容输出到另一个文件吗?

[英]Can a python script output its own contents to another file?

我正在将 python 脚本中的一些数据导出到 Excel 文件,我想知道是否还可以将当前运行的脚本的内容导出到该 Excel 文件。 这将节省我的时间,这样我就不必在每次运行时手动将脚本复制到该 Excel 文件中。

我写Excel没有问题,我唯一的问题是我不知道python是否可以写出自己的脚本内容。

import pandas
excel_file = pandas.ExcelFile("my_file.xlsx")
df = excel_file.parse("sheet_name")
data = df.sample(n=5, random_state=1)

# I would prefer to get the script contents here
# script_contents = ?

with pandas.ExcelWriter("output.xlsx") as writer:
    data.to_excel(writer, sheet_name='Data')
    script_contents.to_excel(writer, sheet_name='Script')

编辑:可能的重复不是一个完整的解决方案,因为它只返回一个字符串,而我的问题需要源代码的 DataFrame。 在下面的答案中查看我的解决方案。

大多数 Python 模块都有一个__file__全局变量,用于指定加载它们的源文件。 假设该脚本全部位于单个模块中,打开该文件并读取它可能是获取脚本源的最简单方法。

with open(__file__) as source_file:
    source = source_file.read()

# do whatever you want with the source string

请参阅如何获取 python 函数的源代码?

如果您的代码是在函数foo()下编写的:

import inspect
lines = inspect.getsource(foo)

变量lines现在保存了函数foo()的源代码。

我在这里找不到其他答案的解决方案,但我确实找到了一种方法来解决这个问题,部分使用了上面评论中提供的链接Gerges

我使用inspect模块来获取脚本内容并将其转换为 DataFrame 以进行导出。 解决方案这是工作解决方案:

import pandas
from pandas.compat import StringIO
import inspect

def sample():
    excel_file = pandas.ExcelFile(r"file.xlsx")
    df = excel_file.parse("Sheet Name")
    random_sample = df.sample(n=5, random_state=1)
    return random_sample

my_sample = sample()
script_text = pandas.read_csv(StringIO(inspect.getsource(inspect.getmodule(inspect.currentframe()))), sep="\n")

with pandas.ExcelWriter('output.xlsx') as writer:
    my_sample.to_excel(writer, sheet_name='Sample', index=False)
    script_text.to_excel(writer, sheet_name='Script', index=False)

暂无
暂无

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

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