简体   繁体   English

使python程序可执行的问题

[英]Issue with making python program executable

I'm trying to make a program so that I can run it through the command line with the following format: 我正在尝试创建一个程序,以便我可以使用以下格式通过命令行运行它:

./myProgram

I made it executable and put #!/usr/bin/env python in the header, but it's giving me the following error. 我把它变成了可执行文件并将#!/usr/bin/env python放在标题中,但它给了我以下错误。

env: python\r: No such file or directory

However, when I run "python myProgram", it runs fine. 但是,当我运行“python myProgram”时,它运行正常。 Can someone tell me what I'm doing wrong? 有人能告诉我我做错了什么吗?

Your line endings are wrong. 你的行结尾是错误的。 Use dos2unix to fix them. 使用dos2unix来修复它们。

+1 on ignacio's suggestion. 关于ignacio的建议+1。

however, to answer the 1st part of your question more directly, each OS/system uses a different line termination character: 但是,为了更直接地回答问题的第1部分,每个OS /系统使用不同的行终止字符:

POSIX (any Unix-flavor like Linux, *BSD, Mac OS X, etc.) uses \\n (NEWLINE) while DOS/Win uses the combo \\r\\n (CR/carriage return + NEWLINE) and old Mac OS 8 or 9 uses just CR or \\r . POSIX(任何Unix风格,如Linux,* BSD,Mac OS X等)使用\\n (NEWLINE)而DOS / Win使用组合\\r\\n (CR /回车+ NEWLINE)和旧Mac OS 8或9仅使用CR或\\r

to solve this problem, you can run a utility like ignacio has suggested, or you should be able to do it from your text editor (may not be very apparent however). 要解决这个问题,您可以运行像ignacio建议的实用程序,或者您应该可以从文本编辑器中执行此操作(但可能不是很明显)。

to answer the other part of your question, the reason why $ python myProgram works is because Python treats all three different line endings the same... the shebang line at the top is ignored because you told Python to load and run that script, and " # " means the first line is a comment and thus ignored. 回答问题的另一部分, $ python myProgram工作原因是因为Python将所有三个不同的行结尾都视为相同...顶部的shebang行被忽略,因为你告诉Python加载并运行该脚本, “ # ”表示第一行是注释,因此被忽略。

when you tell your OS shell to run it, it needs to parse that line and execute whatever interpreter you requested, but if it can't, it pukes on you like it did. 当你告诉你的操作系统shell运行它时,它需要解析该行并执行你请求的任何解释器,但如果它不能,它会像你一样呕吐。

hope this helps! 希望这可以帮助!

ps. PS。 on a side note, you can find out what line-termination character is being used on your operating system, just check out the os.linesep (data) attribute. 在旁注中,您可以找到操作系统上正在使用的行终止字符,只需查看os.linesep (数据)属性即可。 for example, on my Mac (OS X), i get this: 例如,在我的Mac(OS X)上,我得到了这个:

>>> import os
>>> os.linesep
'\n'

here's a quick summary of the other related attributes that i plagiarized from my hardcore Python intro course notes : 这里是我从我的核心Python简介课程笔记中抄袭的其他相关属性的快速摘要: alt text

dos2unix filename.py或在vim内部发出命令:set fileformat=unix并保存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM