简体   繁体   中英

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

I'm exporting some data in my python script to an Excel file and I am wondering if I can also export the contents of the currently-running script to that Excel file. This would save me time so that I do not have to manually copy my script to that Excel file each time I run it.

I have no problems writing to Excel, my only problem is that I do not know if python can write out its own script contents.

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')

EDIT: The possible duplicate isn't a total solution since it only returns a string and my problem needs a DataFrame of the source code. See my solution in the answers below.

Most Python modules have a __file__ global variable that specifies the source file they were loaded from. It may be that opening up that file and reading it is the easiest way to get the source of your script, assuming that script was all in a single module.

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

# do whatever you want with the source string

See How can I get the source code of a python function?

If your code is written under a function foo() :

import inspect
lines = inspect.getsource(foo)

The variable lines now holds the source code for function foo() .

I couldn't find a solution looking at the other answers here but I did find a way for this to work, partially using the link Gerges provided in the comments above.

I used the inspect module to get the script contents and convert it to a DataFrame for export. The solution Here's the working solution:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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