John Smith John Smith - 1 year ago 94
Python Question

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

In, I use a list as input to


cmd = [r'.\', 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.

In .\, the number of arguments are checked:

if len(sys.argv) <= 1:
print('Usage: {0} training_file [testing_file]'.format(sys.argv[0]))
raise SystemExit
runs normally in Python3.3. However, after I changed to Python 3.5. The check
fails, and
is raised. I printed out
and found it now becomes 1. So, how does this happen and how to get correct

My OS is windows 64 bit.

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download