在Windows/Linux/OS X上是否有一种简单的方法来运行Python脚本?在Windows上使用子进程运行Python脚本
在后两种,subprocess.Popen("/the/script.py")
的作品,但在Windows上,我得到以下错误:
Traceback (most recent call last):
File "test_functional.py", line 91, in test_functional
log = tvnamerifiy(tmp)
File "test_functional.py", line 49, in tvnamerifiy
stdout = PIPE
File "C:\Python26\lib\subprocess.py", line 595, in __init__
errread, errwrite)
File "C:\Python26\lib\subprocess.py", line 804, in _execute_child
startupinfo)
WindowsError: [Error 193] %1 is not a valid Win32 application
monkut's comment: The use case isn't clear. Why use subprocess to run a python script? Is there something preventing you from importing the script and calling the necessary function?
我在写一个快速脚本来测试一个Python的命令的整体功能在线工具(在各种平台上测试它)。基本上,它必须在临时文件夹中创建一堆文件,在此文件上运行脚本并检查文件是否正确重命名。
我可以导入脚本和调用的函数,而是因为它依赖于sys.argv
并使用sys.exit()
,我会需要做这样的事情..
import sys
import tvnamer
sys.argv.append("-b", "/the/folder")
try:
tvnamer.main()
except BaseException, errormsg:
print type(errormsg)
另外,我想捕捉到标准输出和stderr进行调试,以防止出现问题。
当然,更好的方法是以更多单元测试的方式编写脚本,但脚本基本上是“完成”的,我在做一个“1.0”版本之前做了最后一批测试(之后我打算做一个重写/重组,这将是更加整洁和更可测试的)
基本上,在找到sys.executable
变量后,简单地运行脚本作为一个进程就容易多了。我会把它写成一个shell脚本,但这不会是跨平台的。最终的脚本,可以发现here
用例不清楚。为什么使用子进程来运行python脚本?有没有办法阻止你导入脚本并调用必要的函数? – monkut 2009-05-27 01:26:05
从python运行nodejs模块时遇到同样的问题。 subprocess.call([r'.. \ nodejs \ npm'],shell = True)解决了这个问题。 – Stefan 2012-11-20 14:00:15