python - 在 python 3.5 中,当使用参数列表作为 subprocess.Popen() 的输入时,我无法获得正确的 len(sys.argv)

标签 python windows python-3.x subprocess sequence

在experiment_script.py中,我使用列表作为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)

在 .\modified_easy.py 中,检查参数数量:

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

experiment_script.py在Python3.3中运行正常。然而,当我改用Python 3.5之后。检查 len(sys.argv) 失败,并引发 SystemExit。我打印出len(sys.argv),发现它现在变成了1。那么,这是如何发生的以及如何获得正确的len(sys.argv)

我的操作系统是 Windows 64 位。

即使我使用 cmd = ' '.join(cmd) 将序列更改为字符串,len(sys.argv) 的结果仍然是 1然后将其输入到subprocess.Popen()

最佳答案

感谢@eryksun 和@J.F.塞巴斯蒂安.我做了一些试验,发现 len(sys.argv) 无法按预期工作。

正如@eryksun所说,

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.

使用 subprocess 在另一个脚本中运行 python 脚本时,如果未指定 python 关键字或 sys.executable,则操作系统会根据一些文件关联来打开.py文件。如果操作系统默认使用 python 启动器 py.exe 打开 .py 文件,那么就可以了。如果操作系统使用 python.exe 打开 .py 文件,则 len(sys.argv) 将失败。

之前我在电脑上安装了Anaconda,并没有py.exe。因此,当“打开方式”对话框询问时,我选择了 python.exe。因此 len(sys.argv) 失败。

要解决这个问题,我可以添加 python 关键字或使用 py.exe 让操作系统打开 .py 文件

关于python - 在 python 3.5 中,当使用参数列表作为 subprocess.Popen() 的输入时,我无法获得正确的 len(sys.argv),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39890879/

相关文章:

python - 来自托盘图标的弹出窗口在窗口关闭时不会关闭程序

python-3.x - python 3 : how to make strip() work for bytes

python-3.x - Firebase - 从另一个帐户导入的用户无法登录

python-3.x - 如何使用 'random' 和 'networkX' 库生成图形?

python - 使列表值成为列表的变量

python - 函数不断返回 None

python - 添加 nltk.download ('words' 后 Google Cloud Run

windows - 如何创建批处理文件以重命名文件夹中的大量文件?

python - 用 Python 抓取文件名的一部分

MySQL 对中型表的查询在一个系统上速度很快,但在另一个系统上速度很慢