【问题标题】:How to implement a program that accepts a file path as its argument?如何实现一个接受文件路径作为参数的程序?
【发布时间】:2017-05-06 14:25:18
【问题描述】:

我编写了一个使用来自文本文件的值的 python 程序。为了获取文本文件,要求之一是它必须能够接受文件路径作为终端中的参数。我正在尝试使用:

# -*- coding: utf-8 -*-
import numpy

x = str(input("Enter directory path: \n"))
data = numpy.loadtxt(open(x), int)

但是,当我像这样在终端中运行程序时:

MBP:Game test$ python GameOfLife.py 
Enter directory path:
/Users/test/Google Drive/Game.py

之后我收到以下错误。

Traceback (most recent call last):
File "Game.py", line 5, in <module>
x = str(input("Enter directory path\n"))
File "<string>", line 1
/Users/test/Google Drive/Game.py
                         ^
SyntaxError: invalid syntax

我是 python 新手,所以任何帮助都会非常棒。

【问题讨论】:

  • 你确定你使用的是 Python 3.X 吗?这看起来像是在 Python 2.X 上使用 input 时会遇到的错误。
  • 您没有使用 Python 3。输入字符串得到 evaled,这是 Python 2 input() 函数的行为。
  • “在终端中接受文件路径作为参数”到底是什么意思?用户应该运行程序然后输入路径,还是应该在启动程序时提供路径,例如py Game.py path/dir/file.py?
  • 我正在使用 Python3。它们在启动程序时提供路径。谢谢

标签: python python-3.x terminal command-line-arguments


【解决方案1】:

字符串必须用引号引起来;

试试这个:

"/Users/test/Google Drive/Game.py"

此外,您可以使用函数raw_input 代替输入。 input 函数将您的输入文本作为 python 代码运行,但使用 raw_input 您可以输入任何内容而不受任何限制。

所以你可以使用

x = raw_input("Enter directory path: \n")

而不是

x = str(input("Enter directory path: \n"))

【讨论】:

  • 或者他们可以切换到raw_input,完全避免input的不安全感。
  • 另外,这里没有可以转义的反斜杠,所以我不知道你为什么提到这一点。
  • 虽然从技术上讲这确实解决了问题,但不应期望用户必须引用他们的输入才能使用该程序。
  • 您好,我使用的是 Python 3,所以这里似乎不起作用
  • 在 python 3 中,raw_input 替换为 input。如果您使用了 python 3,则应该不会出现该错误,因此您可能在 python 2 环境中运行它。运行python --version 或打印sys.version 以确保您的python 是3 :)
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-24
  • 2019-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多