0

I have tried to execute a simple python command from cmd like C:\Users> stat.py < swagger.yaml > output.html, which executes stat.py by taking swagger.yaml as input argument and generates output.html file and it worked fine in cmd. But now i want to execute my stat.py file through another python file demo.py by passing the values swagger.yaml and output.html as sys.argv[0] and sys.argv[1] inside demo.py.

my command from cmd C:\Users> demo.py swagger.yaml output.html and my demo.py file is as follows..

 # my demo.py file ....

import os
import sys

os.system('stat.py < sys.argv[1] > sys.argv[2]')

error - the system can not find the file specified.
Why i am getting this error and please any help to resolve it ..

1 Answer 1

2

Inside a normal string, no variable interpretation is applied. So you literally asked to read from a file named sys.argv[1] (possibly sys.argv1 if the file exists, thanks to shell globbing), and write to a file named sys.argv[2].

If you want to use the values sys.argv in your script, you need to format them into the string, e.g. with f-strings (modern Python 3.6 or so only):

os.system(f'stat.py < {sys.argv[1]} > {sys.argv[2]}')  # Note f at beginning of literal

or on older Python 2.7, with str.format:

os.system('stat.py < {} > {}'.format(sys.argv[1], sys.argv[2]))

Note that however you slice it, this is dangerous; os.system is launching this in a shell, and arguments that contain shell metacharacters will be interpreted as such. It can't do anything the user didn't already have permission to do, but small mistakes by the user could dramatically change the behavior of the program. If you want to do this properly/safely, use subprocess, open the files yourself, and pass them in explicitly as stdin/stdout:

with open(sys.argv[1], 'rb') as infile, open(sys.argv[2], 'wb') as outfile:
    subprocess.run(['stat.py'], stdin=infile, stdout=outfile)

This ensures the files can be opened in the first place before launching the process, doesn't allow the shell to interpret anything, and avoids the (minor) expense of launching a shell at all. It's also going to give you more useful errors if opening the files fails.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.