John Smith John Smith - 1 month ago 11
Python Question

In python 3.5, when using a argument list as input to subprocess.Popen(), I cannot get correct len(sys.argv)

In experiment_script.py, I use a list as input to

subprocess.Popen()
.

cmd = [r'.\modified_easy.py', training_libsvm_files[training_index], testing_libsvm_files[training_index]]
p = subprocess.Popen(cmd,
shell = True, # The cmd won't work without this setting in Python 3.3. However, in Python 3.5, this setting is not necessary.
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)


In .\modified_easy.py, the number of arguments are checked:

if len(sys.argv) <= 1:
print('Usage: {0} training_file [testing_file]'.format(sys.argv[0]))
raise SystemExit


experiment_script.py
runs normally in Python3.3. However, after I changed to Python 3.5. The check
len(sys.argv)
fails, and
SystemExit
is raised. I printed out
len(sys.argv)
and found it now becomes 1. So, how does this happen and how to get correct
len(sys.argv)
?

My OS is windows 64 bit.

The result of
len(sys.argv)
is still 1, even if I use
cmd = ' '.join(cmd)
to change the sequence to a string and then input it to
subprocess.Popen()
.

Answer

Thanks to @eryksun and @J.F. Sebastian . I did some trials and found how len(sys.argv) could not work as expected.

Just as what @eryksun said,

Select "Python" from the list (the py launcher icon has rocket in it) and "always" use this app. Don't "look for another app" because selecting an executable directly creates a new ProgId that doesn't accept command-line arguments.

When running a python script in another script using subprocess, if you don't specify the python keyword or sys.executable, the OS will open the .py file according to some file associations. If the OS by default open .py file with the python launcher py.exe, then it's OK. If the OS open .py file with python.exe then len(sys.argv) will fail.

Previously, I installed Anaconda in a computer and there was no py.exe. So, when asked by the "open with" dialog', I chose python.exe. Therefore len(sys.argv) failed.

To solve it, I can either add the python keyword or make the OS open .py files using py.exe

Comments