-1

I'm trying to call a bash script with python, but I need it to be last thing executed.

I thought just adding this at the end of my script would do it :

val = subprocess.check_call("/scripts/files.sh '%s'" % title,   shell=True)

But it's being executed before the code above it, why?

Last lines above it :

print(q_1)
print(q_2)
print(q_3)
cursor.execute(q_1)
cursor.execute(q_2)
cursor.execute(q_3)
mariadb_connection.commit()
cursor.close()
mariadb_connection.close()

I do use val = subprocess.check_call before all this code to run another bash script too, if that matters

How can I be sure my script will be the last thing executed?

Freedo
  • 121
  • 9
  • There is no way from tae information in your question to figure this out. *Probably* you have some objects which are rigged to run some code to shut down open connections etc when they go out of scope. Voting to close as unclear / unreproducible. – tripleee Feb 08 '20 at 08:31
  • As an aside, if that's tae last statement in your script, surely there is no point in assigning the exit code to a variable? Also, you'll want to [avoid the `shell=True`](/questions/3172470/actual-meaning-of-shell-true-in-subprocess) when you can; `subprocess.check_call(['scripts/files.sh', title])` – tripleee Feb 08 '20 at 08:34
  • It's a very simple script, no functions, threads, anything. It's just a simple script that interacts with an api and do some mysql inserts. – Freedo Feb 08 '20 at 08:46
  • If that is true then this should be easy to salvage. Please [edit] to provide a [mre]. I see nothing to contradict my earlier observations here, though; whatever you are using to talk to MySQL should be explicitly torn down before your final action. – tripleee Feb 08 '20 at 08:49
  • try running your code with python -u my_scrpit.py and report back – marxmacher Feb 08 '20 at 11:46

2 Answers2

0

Python is scripting language, meaning the lines are executed frpm first to last. All you havr to do is place you command at tgr enf of your python script

Azer Gorai
  • 37
  • 1
  • 8
0

Let's assume your script looks something like

obj = MySqlSomething()
things
more things
val = subprocess.check_call(x)

If the class MySqlSomething has a destructor, it will be called after check_call, when you fall off the end of the script and obj goes out of scope. The fix is to make this happen earlier, trivially by moving the stuff into a function:

def main_main():
    obj = MySqlSomething()
    things
    more things

main_main()
val = subprocess.check_call(x)

With this arrangement, obj goes out of scope at the end of main_main.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Another possibility is that `stuff` prints messages to standard error, and stdout gets buffered so that you see it first, or vice versa. Again, as long as we have no idea to repro this, all of this is speculation; and that's why the question should be closed unless you edit it to clarify how exactly to make this happen. – tripleee Feb 08 '20 at 09:04