Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Python run a few lines before my script

I need to run a script foo.py, but I need to also insert some debugging lines to run before the code in foo.py. Currently I just put those lines in foo.py and I'm careful not to commit that to Git, but I don't like this solution.

What I want is a separate file bar.py that I don't commit to Git. Then I want to run:

python /somewhere/bar.py /somewhere_else/foo.py

What I want this to do is first run some lines of code in bar.py, and then run foo.py as __main__. It should be in the same process that the bar.py lines ran in, otherwise the debugging lines won't help.

Is there a way to make bar.py do this?

Someone suggested this:

import imp
import sys

# Debugging code here

fp, pathname, description = imp.find_module(sys.argv[1])
imp.load_module('__main__', fp, pathname, description)

The problem with that is that because it uses import machinery, I need to be on the same folder as foo.py to run that. I don't want that. I want to simply put in the full path to foo.py.

Also: The solution needs to work with .pyc files as well.

like image 209
Ram Rachum Avatar asked Aug 24 '15 14:08

Ram Rachum


People also ask

How do you run multiple lines of code in Python?

You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line. In the revised version of the script, a blank space and an underscore indicate that the statement that was started on line 1 is continued on line 2.

How do I run a Python script from a specific line?

Open the parent script in an interpreter like PyCharm and select the lines you want to execute & then right click -> Execute selection in console.

How do I run a specific line in Python Vscode?

Just click the Run Python File in Terminal play button in the top-right side of the editor. Select one or more lines, then press Shift+Enter or right-click and select Run Selection/Line in Python Terminal. This command is convenient for testing just a part of a file.

How do I run a python script?

Python scripts can be run using Python command over a command line interface. Make sure you specify the path to the script or have the same working directory. To execute your Python script (python_script.py) open command line and write python3 python_script.py

How to make Python wait a few seconds before continuing?

The Python Sleep Function – How to Make Python Wait A Few Seconds Before Continuing, With Example Commands You can use Python’s sleep () function to add a time delay to your code. This function is handy if you want to pause your code between API calls, for example. Or enhance the user’s experience by adding pauses between words or graphics.

How to run Python scripts in idle?

To run Python script using a Python Text Editor you can use the default “run” command or use hot keys like Function + F5 or simply F5 (depending on your OS). Here’s an example of Python script being executed in IDLE. However, note that you do not control the virtual environment like how you typically would from a command line interface execution.

How to write a Python code?

You can write a Python code in interactive and non interactive modes. Once you exit interactive mode, you lose the data. So, sudo nano your_python_filename.py it! You can also run your Python Code via IDE, Code Editors or Command line; There are different ways to import a Python code and use it for another script.


2 Answers

Python has a mechanism for running code at startup; the site module.

"This module is automatically imported during initialization."

The site module will attempt to import a module named sitecustomize before __main__ is imported. It will also attempt to import a module named usercustomize if your environment instructs it to.

For example, you could put a sitecustomize.py file in your site-packages folder that contains this:

import imp

import os

if 'MY_STARTUP_FILE' in os.environ:
    try:
        file_path = os.environ['MY_STARTUP_FILE']
        folder, file_name = os.path.split(file_path)
        module_name, _ = os.path.splitext(file_name)
        fp, pathname, description = imp.find_module(module_name, [folder])
    except Exception as e:
        # Broad exception handling since sitecustomize exceptions are ignored
        print "There was a problem finding startup file", file_path
        print repr(e)
        exit()

    try:
        imp.load_module(module_name, fp, pathname, description)
    except Exception as e:
        print "There was a problem loading startup file: ", file_path
        print repr(e)
        exit()
    finally:
        # "the caller is responsible for closing the file argument" from imp docs
        if fp:
            fp.close()

Then you could run your script like this:

MY_STARTUP_FILE=/somewhere/bar.py python /somewhere_else/foo.py
  • You could run any script before foo.py without needing to add code to reimport __main__.
  • Run export MY_STARTUP_FILE=/somewhere/bar.py and not need to reference it every time
like image 166
Jeremy Allen Avatar answered Oct 15 '22 05:10

Jeremy Allen


You can use execfile() if the file is .py and uncompyle2 if the file is .pyc.

Let's say you have your file structure like:

test|-- foo.py
    |-- bar
         |--bar.py   

foo.py

import sys

a = 1
print ('debugging...')

# run the other file
if sys.argv[1].endswith('.py'): # if .py run right away
    execfile(sys.argv[1], globals(), locals())
elif sys.argv[1].endswith('.pyc'): # if .pyc, first uncompyle, then run
    import uncompyle2
    from StringIO import StringIO
    f = StringIO()
    uncompyle2.uncompyle_file(sys.argv[1], f)
    f.seek(0)
    exec(f.read(), globals(), locals())

bar.py

print a
print 'real job'

And in test/, if you do:

$ python foo.py bar/bar.py
$ python foo.py bar/bar.pyc

Both, outputs the same:

debugging...
1
real job

Please also see this answer.

like image 43
Sait Avatar answered Oct 15 '22 05:10

Sait