pypreprocessor
pypreprocessor copied to clipboard
Import not working inside def (function)
I used the debug2production.py script as a base. When I try to use a function from an import inside a function that I created, it says the name of the import (time, in my example) is not defined (line 40). Everything works fine when I don't use functions. Also, the script only runs directly if __name__ == 'pypreprocessor'. If only __name__ =='__main__' is used, it only runs on the output file without preprocessing.
import sys
import time
from pypreprocessor import pypreprocessor
outputFile = 'output_file.py'
start_time = time.time()
#exclude
# run the script in 'debug' mode
if 'debug' in sys.argv:
pypreprocessor.defines.append('debug')
# run the script in 'production' mode
if 'production' in sys.argv:
pypreprocessor.defines.append('production')
pypreprocessor.output = outputFile
pypreprocessor.removeMeta = True
# run the script in 'postprocessed' mode
if 'postprocessed' in sys.argv:
pypreprocessor.defines.append('postprocessed')
pypreprocessor.output = outputFile
pypreprocessor.parse()
#endexclude
def do_stuff():
global outputFile, start_time
#ifdef debug
print('This script is running in \'debug\' mode')
#else
#ifdef production
print('This script is running in \'production\' mode')
print('To see the output open ' + outputFile)
#else
#ifdef postprocessed
print('This script is running in \'postprocessed\' mode')
print('To see the output open ' + outputFile)
#endifall
print(time.time()-start_time)
if __name__ == '__main__' or __name__ == 'pypreprocessor':
do_stuff()
It may seem counter-intuitive but try placing the imports after the call to parse()
The magic behind this lib is that it hijacks the imp module, preprocesses the source in memory, they imports the postprocessed source directly from memory. Producing a bytecode file that reflects the postprocessed source.
That means any imports that happen prior to the call to parse() are invisible to the postprocessed source.
If you don't like the 'magic' behavior, you could always opt to define the preprocessing step as it's own script and apply it to an external file. There should be no side-effects to this approach.
Calling import time and start_time = time.time() after parse() still gives the same error: "name 'time' is not defined" at print(time.time()-start_time), but start_time = time.time() that is outside the def is working just as before. Using the postprocessed file is working fine when running the source file only for preprocessing, but I would like to run everything with a single file. I also don't understand how to use a script to preprocess an external file. A working example in the repository would help.
I managed to run an external code with import, but still have the same issue. I will keep editing the source file and executing the output postprocessed