Search code examples
pythonargumentscall

Calling a python script from another python script with arguments does not work


I am well aware that there are multiple threads dealing with this problem because I used them in an attempt to self-teach me how to do it. However, for me it does not work and I wondered if someone could help me find my error.

So I got one program (let's call it prog1) that calls a script for every string-variable like this:

os.system(r'C:\Users\user\docs\bla\script.py %s'%variable)

In script.py I now just wanted to test if this call worked by disabling all code but just doing:

def main(string):
    print(string)
    root

if __name__ == "__main__":
    print('I got executed')
    main(sys.argv[1])

The Problem is, if I execute prog1 nothing happens. No errer - so it runs through and the console pops up for a Brief second. However, nothing happens - no string is printed. If I execute script.py directly it works though.

EDIT: I got it to execute without error with the subprocess package by using:

subprocess.call(r'C:\...\script.py' %s' %variable,shell = True)

However, the problem stays the same - nothing happens. Or well, I noticed now that in the Background a Windows window pops up asking me with which program I want to execute files with the ending '.py' but this is not helping me, because I want to execute in console :(


Solution

  • Try using the subprocess module, it allows for more flexible parametres and other configuration changes :

    import subprocess
    subprocess.check_call(["python.exe", r"C:\Users\user\docs\bla\script.py", variable])
    

    And when executed :

    subprocess.check_call(["python", r"C:\Users\user\docs\bla\script.py", "Blue"])
    

    I got executed

    Blue

    More information about the subprocess : https://docs.python.org/2/library/subprocess.html