Madh
Madh

Reputation: 33

Run a script from different folder with arguments in python (like in cmd)

I guess I have to use either use os.system or subprocess.call, but I can't figure out how to use it.

I don't have the permission to edit the original folder.

subprocess.Popen('file.py', cwd=dirName) gives me 'The system cannot find the file specified' even though the file clearly exists

If I was typing in cmd,

cd directory
file.py -arg

Edit: Just to be clear I want to run another script using a python script

Upvotes: 0

Views: 900

Answers (3)

Eamonn Kenny
Eamonn Kenny

Reputation: 2072

Its clear you are probably using python 3 rather than python 2. Otherwise you might use os.system as already suggested or commands. Commands is now obsolete as of python 3. To get this working I would use instead:

statusAndOutputText = subprocess.getstatusoutput( os.path.join( dirName, 'file.py' ) )

This will definitely work. I've used it many times in python 3 and it will give you the status in statusAndOutputText[0] and output buffer in statusAndOutputText[1] which are both very useful to have.

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 149185

As you have tagged the question with cmd, I assume that you use Windows. Windows is kind enough to automatically use the appropriate command when you type a document name in cmd, but Python subprocess is not. So you have 2 possible ways here

  1. use shell=True to ask a cmd interpretor to execute the command:

    subprocess.Popen('file.py', cwd=dirName, shell=True)
    
  2. pass explicitely the path of the Python interpretor (or the name if it is in the path)

    subprocess.Popen([python_path, 'file.py'], cwd=dirName, shell=True)
    

Upvotes: 1

amirhosein majidi
amirhosein majidi

Reputation: 149

At first you need to add the python in windows environment. Then you can add the file path (the file that you want to run it on command line). Then you can go to command line page and type the file name and use it like the line below:

FileName commands

for example :

pip install datetime

Upvotes: 0

Related Questions