简体   繁体   中英

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

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) 

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM