我想实现从Windows到Linux的Popen代码:

问题描述 投票:1回答:1

我想实现从Windows到Linux的这段代码:

a=subprocess.Popen(['python.exe','hello.py'])
python python-3.x subprocess popen
1个回答
0
投票

有两个问题。首先,python.exe在Linux中简称为python,其次是python可执行文件不在当前目录中,而是在系统路径中的某个位置。要让Linux在路径中查找python,您可以让Popen使用shell:

a=subprocess.Popen(['python','hello.py'], shell=True)

或者您可以使用env程序找到它:

a=subprocess.Popen(['/usr/bin/env', 'python','hello.py'])

作为第三种选择,您可以使用Linux shebang方法启动hello.py脚本,并让Windows文件关联在python解释器中运行hello.py,做三件事:

  1. 将hello.py的第一行设为#!/usr/bin/env python
  2. 通过执行chmod a+x hello.py将文件hello.py标记为Linux中的可执行文件。
  3. 在shell中运行hello.py脚本 a=subprocess.Popen('hello.py', shell=True)

这将使脚本在Windows和Linux中以相同的方式工作。

请注意shebang行:hello.py必须使用UNIX行结束约定保存,否则会出现模糊的'python not found'错误。这是由Windows编辑器添加的额外'\ n'引起的,让shell查找名为'python\n'的文件 - 当然不存在。您可以使用hello.py工具将dos2unix转换为UNIX行结尾。一旦设置为UNIX,所有可敬的文件编辑器将保留行结尾。

© www.soinside.com 2019 - 2024. All rights reserved.