标签归档:linux

如何在Linux和Windows中的Python中使用“ /”(目录分隔符)?

问题:如何在Linux和Windows中的Python中使用“ /”(目录分隔符)?

我已经在python中编写了一个代码,该代码使用/在文件夹中创建特定文件,如果我想在Windows中使用该代码将无法正常工作,有没有一种方法可以在Windows和Linux中使用该代码。

在python中,我使用以下代码:

pathfile=os.path.dirname(templateFile)
rootTree.write(''+pathfile+'/output/log.txt')

当我在Windows计算机中使用我的代码时,我的代码将无法工作。

在Linux和Windows中如何使用“ /”(目录分隔符)?

I have written a code in python which uses / to make a particular file in a folder, if I want to use the code in windows it will not work, is there a way by which I can use the code in Windows and Linux.

In python I am using this code:

pathfile=os.path.dirname(templateFile)
rootTree.write(''+pathfile+'/output/log.txt')

When I will use my code in suppose windows machine my code will not work.

How do I use “/” (directory separator) in both Linux and Windows?


回答 0

使用os.path.join()。范例:os.path.join(pathfile,"output","log.txt")

在您的代码中将是: rootTree.write(os.path.join(pathfile,"output","log.txt"))

Use os.path.join(). Example: os.path.join(pathfile,"output","log.txt").

In your code that would be: rootTree.write(os.path.join(pathfile,"output","log.txt"))


回答 1

用:

import os
print os.sep

查看分隔符在当前操作系统上的外观。
在您的代码中,您可以使用:

import os
path = os.path.join('folder_name', 'file_name')

Use:

import os
print os.sep

to see how separator looks on a current OS.
In your code you can use:

import os
path = os.path.join('folder_name', 'file_name')

回答 2

您可以使用os.sep

>>> import os
>>> os.sep
'/'

You can use os.sep:

>>> import os
>>> os.sep
'/'

回答 3

os.path.normpath(pathname)还应提及,因为它将Windows上的/路径分隔符转换为\分隔符。它还折叠冗余uplevel引用…即,A/BA/foo/../BA/./B一切变得A/B。如果您使用的是Windows,那么所有这些都将变为A\B

os.path.normpath(pathname) should also be mentioned as it converts / path separators into \ separators on Windows. It also collapses redundant uplevel references… i.e., A/B and A/foo/../B and A/./B all become A/B. And if you are Windows, these all become A\B.


回答 4

如果您有幸能够运行Python 3.4+,则可以使用pathlib

from pathlib import Path

path = Path(dir, subdir, filename)  # returns a path of the system's path flavour

或者,等效地,

path = Path(dir) / subdir / filename

If you are fortunate enough to be running Python 3.4+, you can use pathlib:

from pathlib import Path

path = Path(dir, subdir, filename)  # returns a path of the system's path flavour

or, equivalently,

path = Path(dir) / subdir / filename

回答 5

一些有用的链接将帮助您:

Some useful links that will help you:


回答 6

做一个import os然后使用os.sep

Do a import os and then use os.sep


回答 7

您可以使用“ os.sep

 import os
 pathfile=os.path.dirname(templateFile)
 directory = str(pathfile)+os.sep+'output'+os.sep+'log.txt'
 rootTree.write(directory)

You can use “os.sep

 import os
 pathfile=os.path.dirname(templateFile)
 directory = str(pathfile)+os.sep+'output'+os.sep+'log.txt'
 rootTree.write(directory)

回答 8

不要自行建立目录和文件名,请使用python随附的库。

在这种情况下,相关的是os.path。特别是join,它从目录和文件名或目录创建一个新的路径名,然后从完整路径中获取文件名。

你的例子是

pathfile=os.path.dirname(templateFile)
p = os.path.join(pathfile, 'output')
p = os.path.join( p, 'log.txt')
rootTree.write(p)

Don’t build directory and file names your self, use python’s included libraries.

In this case the relevant one is os.path. Especially join which creates a new pathname from a directory and a file name or directory and split that gets the filename from a full path.

Your example would be

pathfile=os.path.dirname(templateFile)
p = os.path.join(pathfile, 'output')
p = os.path.join( p, 'log.txt')
rootTree.write(p)

Pwntools-CTF框架和开发开发库

pwntools-CTF工具包

Pwntools是一个CTF框架和开发开发库。它是用Python编写的,专为快速原型和开发而设计,旨在使利用代码尽可能简单

from pwn import *
context(arch = 'i386', os = 'linux')

r = remote('exploitme.example.com', 31337)
# EXPLOIT CODE GOES HERE
r.send(asm(shellcraft.sh()))
r.interactive()

文档

我们的文档位于docs.pwntools.com

还提供了一系列教程available online

为了帮助您入门,我们为过去的CTF挑战提供了一些示例解决方案,在我们的write-ups repository

安装

Pwntools最受64位Ubuntu LTS版本(14.04、16.04、18.04和20.04)的支持。大多数功能应该适用于任何类似POSIX的发行版(Debian、Arch、FreeBSD、OSX等)

建议使用Python3,但Pwntools仍然适用于Python2.7。pwntools的大部分功能都是自包含的,并且只支持Python。您应该能够快速使用

apt-get update
apt-get install python3 python3-pip python3-dev git libssl-dev libffi-dev build-essential
python3 -m pip install --upgrade pip
python3 -m pip install --upgrade pwntools

但是,某些特性(组装/反汇编外来体系结构)需要非Python依赖项。有关更多信息,请参阅complete installation instructions here

贡献

看见CONTRIBUTING.md

联系方式和社区

如果您有任何不值得回答的问题bug report,加入不一致服务器,地址为https://discord.gg/96VA2zvjCB

如何在管道上使用`subprocess`命令

问题:如何在管道上使用`subprocess`命令

我想搭配subprocess.check_output()使用ps -A | grep 'process_name'。我尝试了各种解决方案,但到目前为止没有任何效果。有人可以指导我怎么做吗?

I want to use subprocess.check_output() with ps -A | grep 'process_name'. I tried various solutions but so far nothing worked. Can someone guide me how to do it?


回答 0

要将管道与subprocess模块一起使用,必须通过shell=True

但是,出于种种原因,这并不是真正可取的选择,其中不仅包括安全性。相反,请分别创建psgrep流程,并将输出从一个管道传递到另一个管道,如下所示:

ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)
output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)
ps.wait()

但是,在您的特定情况下,简单的解决方案是先调用subprocess.check_output(('ps', '-A'))然后str.find在输出上。

To use a pipe with the subprocess module, you have to pass shell=True.

However, this isn’t really advisable for various reasons, not least of which is security. Instead, create the ps and grep processes separately, and pipe the output from one into the other, like so:

ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)
output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)
ps.wait()

In your particular case, however, the simple solution is to call subprocess.check_output(('ps', '-A')) and then str.find on the output.


回答 1

或者,您始终可以在子流程对象上使用communication方法。

cmd = "ps -A|grep 'process_name'"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print(output)

通信方法返回标准输出和标准错误的元组。

Or you can always use the communicate method on the subprocess objects.

cmd = "ps -A|grep 'process_name'"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print(output)

The communicate method returns a tuple of the standard output and the standard error.


回答 2

请参阅有关使用子流程设置管道的文档:http : //docs.python.org/2/library/subprocess.html#replacing-shell-pipeline

我没有测试下面的代码示例,但是它应该大致是您想要的:

query = "process_name"
ps_process = Popen(["ps", "-A"], stdout=PIPE)
grep_process = Popen(["grep", query], stdin=ps_process.stdout, stdout=PIPE)
ps_process.stdout.close()  # Allow ps_process to receive a SIGPIPE if grep_process exits.
output = grep_process.communicate()[0]

See the documentation on setting up a pipeline using subprocess: http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline

I haven’t tested the following code example but it should be roughly what you want:

query = "process_name"
ps_process = Popen(["ps", "-A"], stdout=PIPE)
grep_process = Popen(["grep", query], stdin=ps_process.stdout, stdout=PIPE)
ps_process.stdout.close()  # Allow ps_process to receive a SIGPIPE if grep_process exits.
output = grep_process.communicate()[0]

回答 3

JKALAVIS解决方案很好,但是我将使用shlex代替SHELL = TRUE进行改进。下面即时查询时间

#!/bin/python
import subprocess
import shlex

cmd = "dig @8.8.4.4 +notcp www.google.com|grep 'Query'"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print(output)

JKALAVIS solution is good, however I would add an improvement to use shlex instead of SHELL=TRUE. below im grepping out Query times

#!/bin/python
import subprocess
import shlex

cmd = "dig @8.8.4.4 +notcp www.google.com|grep 'Query'"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print(output)

回答 4

另外,尝试使用'pgrep'命令代替'ps -A | grep 'process_name'

Also, try to use 'pgrep' command instead of 'ps -A | grep 'process_name'


回答 5

您可以在sh.py中尝试管道功能:

import sh
print sh.grep(sh.ps("-ax"), "process_name")

You can try the pipe functionality in sh.py:

import sh
print sh.grep(sh.ps("-ax"), "process_name")

回答 6

Python 3.5之后,您还可以使用:

    import subprocess

    f = open('test.txt', 'w')
    process = subprocess.run(['ls', '-la'], stdout=subprocess.PIPE, universal_newlines=True)
    f.write(process.stdout)
    f.close()

该命令的执行被阻止,输出将在process.stdout中

After Python 3.5 you can also use:

    import subprocess

    f = open('test.txt', 'w')
    process = subprocess.run(['ls', '-la'], stdout=subprocess.PIPE, universal_newlines=True)
    f.write(process.stdout)
    f.close()

The execution of the command is blocking and the output will be in process.stdout.


如何激活virtualenv?

问题:如何激活virtualenv?

我一直在搜索,尝试了各种替代方法都没有成功,现在花了几天时间-令我发疯。

在具有Python 2.5.2的Red Hat Linux上运行开始使用最新的Virtualenv,但无法激活它,我发现某个地方提示需要较早的版本,因此我使用Virtualenv 1.6.4,因为它应可与Python 2.6一起使用。

看来安装虚拟环境还可以

[necrailk@server6 ~]$ python virtualenv-1.6.4/virtualenv.py virtual
New python executable in virtual/bin/python
Installing setuptools............done.
Installing pip...............done.

环境看起来还可以

[necrailk@server6 ~]$ cd virtual
[necrailk@server6 ~/virtual]$ dir
bin  include  lib

试图激活

[necrailk@server6 ~/virtual]$ . bin/activate
/bin/.: Permission denied.

已检查chmod

[necrailk@server6 ~/virtual]$ cd bin
[necrailk@server6 bin]$ ls -l
total 3160
-rw-r--r--    1 necrailk biz12        2130 Jan 30 11:38 activate
-rw-r--r--    1 necrailk biz12        1050 Jan 30 11:38 activate.csh
-rw-r--r--    1 necrailk biz12        2869 Jan 30 11:38 activate.fish
-rw-r--r-

问题,所以我改变了

[necrailk@server6 bin]$ ls -l
total 3160
-rwxr--r--    1 necrailk biz12        2130 Jan 30 11:38 activate
-rw-r--r--    1 necrailk biz12        1050 Jan 30 11:38 activate.csh
-rw-r--r--    1 necrailk biz12        2869 Jan 30 11:38 activate.fish
-rw-r--r--    1 necrailk biz12        1005 Jan 30 11:38 activate_this.py
-rwxr-xr-x    1 necrailk biz

再试activate一次

[necrailk@server6 ~/virtual]$ . bin/activate
/bin/.: Permission denied.

仍然没有喜悦…

I have been through search and tried various alternatives without success and spent several days on it now – driving me mad.

Running on Red Hat Linux with Python 2.5.2 Began using most recent Virtualenv but could not activate it, I found somewhere suggesting needed earlier version so I have used Virtualenv 1.6.4 as that should work with Python 2.6.

It seems to install the virtual environment ok

[necrailk@server6 ~]$ python virtualenv-1.6.4/virtualenv.py virtual
New python executable in virtual/bin/python
Installing setuptools............done.
Installing pip...............done.

Environment looks ok

[necrailk@server6 ~]$ cd virtual
[necrailk@server6 ~/virtual]$ dir
bin  include  lib

Trying to activate

[necrailk@server6 ~/virtual]$ . bin/activate
/bin/.: Permission denied.

Checked chmod

[necrailk@server6 ~/virtual]$ cd bin
[necrailk@server6 bin]$ ls -l
total 3160
-rw-r--r--    1 necrailk biz12        2130 Jan 30 11:38 activate
-rw-r--r--    1 necrailk biz12        1050 Jan 30 11:38 activate.csh
-rw-r--r--    1 necrailk biz12        2869 Jan 30 11:38 activate.fish
-rw-r--r-

Problem, so I changed it

[necrailk@server6 bin]$ ls -l
total 3160
-rwxr--r--    1 necrailk biz12        2130 Jan 30 11:38 activate
-rw-r--r--    1 necrailk biz12        1050 Jan 30 11:38 activate.csh
-rw-r--r--    1 necrailk biz12        2869 Jan 30 11:38 activate.fish
-rw-r--r--    1 necrailk biz12        1005 Jan 30 11:38 activate_this.py
-rwxr-xr-x    1 necrailk biz

Try activate again

[necrailk@server6 ~/virtual]$ . bin/activate
/bin/.: Permission denied.

Still no joy…


回答 0

这是创建文件夹并将cd其放入后的工作流程:

$ virtualenv venv --distribute
New python executable in venv/bin/python
Installing distribute.........done.
Installing pip................done.
$ source venv/bin/activate
(venv)$ python

Here is my workflow after creating a folder and cd‘ing into it:

$ virtualenv venv --distribute
New python executable in venv/bin/python
Installing distribute.........done.
Installing pip................done.
$ source venv/bin/activate
(venv)$ python

回答 1

您忘了source bin/activate在source是可执行文件名称的地方做。同样也打了我几次,容易想到手册说的是“从环境文件夹的根目录执行此操作”。

无需activate通过执行chmod

You forgot to do source bin/activate where source is a executable name. Struck me first few times as well, easy to think that manual is telling “execute this from root of the environment folder”.

No need to make activate executable via chmod.


回答 2

你可以做

source ./python_env/bin/activate

或只是转到目录

cd /python_env/bin/

然后

source ./activate

祝好运。

You can do

source ./python_env/bin/activate

or just go to the directory

cd /python_env/bin/

and then

source ./activate

Good Luck.


回答 3

将CD复制到环境路径,然后转到bin文件夹。此时,当您使用ls命令时,应该会看到“激活”文件。

现在输入

source activate

Cd to the environment path, go to the bin folder. At this point when you use ls command, you should see the “activate” file.

now type

source activate

回答 4

转到项目目录。在我的情况下microblog是flask项目目录,在microblog目录下应该有appvenv文件夹。然后运行以下命令,这是在Ubuntu中为我工作的命令。

source venv/bin/activate

Go to the project directory. In my case microblog is the flask project directory and under microblog directory there should be app and venv folders. then run the below command, This is one worked for me in Ubuntu.

source venv/bin/activate


回答 5

问题出在/bin/.命令。从那以来,那真的很奇怪。应该始终是它所在目录的链接。(老实说,除非.是一个奇怪的别名或函数,否则我什至不知道这是不可能的。)shell没有. 内置的forsource也是有点不寻常

一种快速的解决方法是仅在另一个Shell中运行virtualenv。(一个明显的第二个优势是,deactivate您不必仅仅拥有即可exit。)

/bin/bash --rcfile bin/activate

如果您的外壳支持它,则您可能还具有非标准source命令,该命令应与做相同的事情.,但可能不存在。(总而言之,您应该尝试弄清楚为什么您的环境很奇怪,否则将来会再次让您痛苦。)

顺便说一句,您不需要chmod +x这些文件。仅当您要直接执行文件时,才需要文件是可执行文件。在这种情况下,您尝试从中启动它们.,因此他们不需要它。

The problem there is the /bin/. command. That’s really weird, since . should always be a link to the directory it’s in. (Honestly, unless . is a strange alias or function, I don’t even see how it’s possible.) It’s also a little unusual that your shell doesn’t have a . builtin for source.

One quick fix would be to just run the virtualenv in a different shell. (An obvious second advantage being that instead of having to deactivate you can just exit.)

/bin/bash --rcfile bin/activate

If your shell supports it, you may also have the nonstandard source command, which should do the same thing as ., but may not exist. (All said, you should try to figure out why your environment is strange or it will cause you pain again in the future.)

By the way, you didn’t need to chmod +x those files. Files only need to be executable if you want to execute them directly. In this case you’re trying to launch them from ., so they don’t need it.


回答 6

$ mkdir <YOURPROJECT> 创建一个新项目

$ cd <YOURPROJECT> 将目录更改为该项目

$ virtualenv <NEWVIRTUALENV> 创建新的virtualenv

$ source <NEWVIRTUALENV>/bin/activate 激活新的virtualenv

$ mkdir <YOURPROJECT> Create a new project

$ cd <YOURPROJECT> Change directory to that project

$ virtualenv <NEWVIRTUALENV> Creating new virtualenv

$ source <NEWVIRTUALENV>/bin/activate Activating that new virtualenv


回答 7

代替 ./activate

source activate

instead of ./activate

use source activate


回答 8

对于Windows,您可以执行以下操作:

创建虚拟环境的方式为:virtualenv envName –python = python.exe(如果未创建环境变量)

激活虚拟环境:> \ path \ to \ envName \ Scripts \ activate

要停用虚拟环境:> \ path \ to \ env \ Scripts \ deactivate

可以在新的python版本上正常工作。

For Windows You can perform as:

TO create the virtual env as: virtualenv envName –python=python.exe (if not create environment variable)

To activate the virtual env : > \path\to\envName\Scripts\activate

To deactivate the virtual env : > \path\to\env\Scripts\deactivate

It fine works on the new python version .


回答 9

source virtualen_name/bin/activate

source virtualen_name/bin/activate


回答 10

我也会推荐virtualenvwrapper。它为我创造了奇迹,以及我在激活方面总是遇到问题。http://virtualenvwrapper.readthedocs.org/en/latest/

I would recommend virtualenvwrapper as well. It works wonders for me and how I always have problems with activating. http://virtualenvwrapper.readthedocs.org/en/latest/


回答 11

创建名为的自己的Python虚拟环境<Your Env _name >:。我给它VE。

git clone https://github.com/pypa/virtualenv.git
python virtualenv.py VE

要激活您的新虚拟环境,请运行(注意不在./此处):

. VE/bin/activate

示例输出(注释提示已更改):

(VE)c34299@a200dblr$

设置虚拟环境后,即可删除该存储Virtualenv库。

Create your own Python virtual environment called <Your Env _name >:. I have given it VE.

git clone https://github.com/pypa/virtualenv.git
python virtualenv.py VE

To activate your new virtual environment, run (notice it’s not ./ here):

. VE/bin/activate

Sample output (note prompt changed):

(VE)c34299@a200dblr$

Once your virtual environment is set, you can remove the Virtualenv repo.


回答 12

在Mac上,将shell更改为BASH(请注意,虚拟环境仅在bash shell中有效)

[user@host tools]$. venv/bin/activate 

.: Command not found.

[user@host tools]$source venv/bin/activate

Badly placed ()'s.

[user@host tools]$bash

bash-3.2$ source venv/bin/activate

(venv) bash-3.2$ 

宾果游戏,它奏效了。看到提示更改。

在Ubuntu上:

user@local_host:~/tools$ source toolsenv/bin/activate

(toolsenv) user@local_host~/tools$ 

注意:提示更改

On Mac, change shell to BASH (keep note that virtual env works only in bash shell )

[user@host tools]$. venv/bin/activate 

.: Command not found.

[user@host tools]$source venv/bin/activate

Badly placed ()'s.

[user@host tools]$bash

bash-3.2$ source venv/bin/activate

(venv) bash-3.2$ 

Bingo , it worked. See prompt changed.

On Ubuntu:

user@local_host:~/tools$ source toolsenv/bin/activate

(toolsenv) user@local_host~/tools$ 

Note : prompt changed


回答 13

我在运行源代码/ bin / activate时遇到了麻烦,然后我意识到我将tcsh用作终端shell而不是bash。切换后,我便可以激活venv。

I had trouble getting running source /bin/activate then I realized I was using tcsh as my terminal shell instead of bash. once I switched I was able to activate venv.


回答 14

Windows 10

在Windows中,将创建以下目录:

在Windows 10中激活虚拟环境。

down\scripts\activate

\ scripts目录包含激活文件。

Linux Ubuntu

在Ubuntu中,将创建以下目录:

在Linux Ubuntu中激活虚拟环境。

source ./bin/activate

/ bin目录包含激活文件。


虚拟环境从Windows复制到Linux Ubuntu反之亦然

如果将虚拟环境文件夹从Windows复制到Linux Ubuntu,则根据目录:

source ./down/Scripts/activate

Windows 10

In Windows these directories are created :

To activate Virtual Environment in Windows 10.

down\scripts\activate

\scripts directory contain activate file.

Linux Ubuntu

In Ubuntu these directories are created :

To activate Virtual Environment in Linux Ubuntu.

source ./bin/activate

/bin directory contain activate file.


Virtual Environment copied from Windows to Linux Ubuntu vice versa

If Virtual environment folder copied from Windows to Linux Ubuntu then according to directories:

source ./down/Scripts/activate

回答 15

运行此代码,如果您在Windows计算机上,它将被激活
source venv/Scripts/activate

run this code it will get activated if you on a windows machine
source venv/Scripts/activate


回答 16

在这里发布我的答案可能有点晚了,但我仍然会发布,尽管这样做可能会使某人受益,

我曾经遇到过同样的问题,

主要原因是我以“ root”用户身份创建了virtualenv,但后来尝试使用另一个用户激活它。

chmod不能工作,因为您不是文件的所有者,因此替代方法是使用chown(更改所有权)

例如:

如果您在/ home / abc / ENV中创建了virtualenv

然后CD到/ home / abc

并运行以下命令:chown -Rv [您想要更改所有权的用户] [需要更改所有权的文件夹/文件名]

在此示例中,命令为:chown -Rv abc ENV

成功更改所有权后,您只需运行源/ENV/bin/./activate,您就应该能够正确激活virtualenv。

Probably a little late to post my answer here but still I’ll post, it might benefit someone though,

I had faced the same problem,

The main reason being that I created the virtualenv as a “root” user But later was trying to activate it using another user.

chmod won’t work as you’re not the owner of the file, hence the alternative is to use chown (to change the ownership)

For e.g. :

If you have your virtualenv created at /home/abc/ENV

Then CD to /home/abc

and run the command : chown -Rv [user-to-whom-you want-change-ownership] [folder/filename whose ownership needs to be changed]

In this example the commands would be : chown -Rv abc ENV

After the ownership is successfully changed you can simply run source /ENV/bin/./activate and your should be able to activate the virtualenv correctly.


回答 17

1-打开powershell并导航到您的应用程序文件夹2-输入您的virtualenv文件夹,例如:cd。\ venv \ Scripts \ 3-通过键入。\ activate激活virtualenv

1- open powershell and navigate to your application folder 2- enter your virtualenv folder ex : cd .\venv\Scripts\ 3- active virtualenv by type .\activate


如何在Python中获取Linux控制台窗口宽度

问题:如何在Python中获取Linux控制台窗口宽度

python中有没有办法以编程方式确定控制台的宽度?我的意思是不换行就适合一行的字符数,而不是窗口的像素宽度。

编辑

寻找适用于Linux的解决方案

Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.

Edit

Looking for a solution that works on Linux


回答 0

import os
rows, columns = os.popen('stty size', 'r').read().split()

使用“ stty size”命令,该命令根据python邮件列表上的线程在linux上相当普遍。它以文件形式打开“ stty size”命令,并从中“读取”,并使用简单的字符串拆分来分隔坐标。

与os.environ [“ COLUMNS”]值(尽管使用bash作为我的标准Shell不能访问)不同,数据也将是最新的,而我相信os.environ [“ COLUMNS”]该值仅在python解释器启动时有效(假设从那时起用户调整了窗口的大小)。

(有关如何在python 3.3+上执行此操作,请参见@GringoSuave的回答)

import os
rows, columns = os.popen('stty size', 'r').read().split()

uses the ‘stty size’ command which according to a thread on the python mailing list is reasonably universal on linux. It opens the ‘stty size’ command as a file, ‘reads’ from it, and uses a simple string split to separate the coordinates.

Unlike the os.environ[“COLUMNS”] value (which I can’t access in spite of using bash as my standard shell) the data will also be up-to-date whereas I believe the os.environ[“COLUMNS”] value would only be valid for the time of the launch of the python interpreter (suppose the user resized the window since then).

(See answer by @GringoSuave on how to do this on python 3.3+)


回答 1

不知道为什么它在模块中shutil,但是它在Python 3.3中降落在那里,查询输出终端的大小

>>> import shutil
>>> shutil.get_terminal_size((80, 20))  # pass fallback
os.terminal_size(columns=87, lines=23)  # returns a named-tuple

os模块中有一个底层实现。在Windows中也可以使用。

反向移植现在可用于Python 3.2及以下版本:

Not sure why it is in the module shutil, but it landed there in Python 3.3, Querying the size of the output terminal:

>>> import shutil
>>> shutil.get_terminal_size((80, 20))  # pass fallback
os.terminal_size(columns=87, lines=23)  # returns a named-tuple

A low-level implementation is in the os module. Also works in Windows.

A backport is now available for Python 3.2 and below:


回答 2

import console
(width, height) = console.getTerminalSize()

print "Your terminal's width is: %d" % width

编辑:哦,对不起。那不是python标准库,这是console.py的来源(我不知道它来自哪里)。

该模块似乎像这样工作:检查是否termcap可用,何时可用。它使用它;如果不是,它将检查终端是否支持特殊ioctl调用,并且该调用也不起作用,它将检查某些shell为此导出的环境变量。这可能仅适用于UNIX。

def getTerminalSize():
    import os
    env = os.environ
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
        '1234'))
        except:
            return
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        cr = (env.get('LINES', 25), env.get('COLUMNS', 80))

        ### Use get(key[, default]) instead of a try/catch
        #try:
        #    cr = (env['LINES'], env['COLUMNS'])
        #except:
        #    cr = (25, 80)
    return int(cr[1]), int(cr[0])

use

import console
(width, height) = console.getTerminalSize()

print "Your terminal's width is: %d" % width

EDIT: oh, I’m sorry. That’s not a python standard lib one, here’s the source of console.py (I don’t know where it’s from).

The module seems to work like that: It checks if termcap is available, when yes. It uses that; if no it checks whether the terminal supports a special ioctl call and that does not work, too, it checks for the environment variables some shells export for that. This will probably work on UNIX only.

def getTerminalSize():
    import os
    env = os.environ
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
        '1234'))
        except:
            return
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        cr = (env.get('LINES', 25), env.get('COLUMNS', 80))

        ### Use get(key[, default]) instead of a try/catch
        #try:
        #    cr = (env['LINES'], env['COLUMNS'])
        #except:
        #    cr = (25, 80)
    return int(cr[1]), int(cr[0])

回答 3

上面的代码未在我的Linux上返回正确的结果,因为winsize-struct有4条未签名的短裤,而不是2条已签名的短裤:

def terminal_size():
    import fcntl, termios, struct
    h, w, hp, wp = struct.unpack('HHHH',
        fcntl.ioctl(0, termios.TIOCGWINSZ,
        struct.pack('HHHH', 0, 0, 0, 0)))
    return w, h

hp和hp应该包含像素的宽度和高度,但不包含。

Code above didn’t return correct result on my linux because winsize-struct has 4 unsigned shorts, not 2 signed shorts:

def terminal_size():
    import fcntl, termios, struct
    h, w, hp, wp = struct.unpack('HHHH',
        fcntl.ioctl(0, termios.TIOCGWINSZ,
        struct.pack('HHHH', 0, 0, 0, 0)))
    return w, h

hp and hp should contain pixel width and height, but don’t.


回答 4

我四处搜寻,找到了Windows的解决方案:

http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/

以及适用于Linux的解决方案。

所以这是一个可以在linux,os x和Windows / cygwin上运行的版本:

""" getTerminalSize()
 - get width and height of console
 - works on linux,os x,windows,cygwin(windows)
"""

__all__=['getTerminalSize']


def getTerminalSize():
   import platform
   current_os = platform.system()
   tuple_xy=None
   if current_os == 'Windows':
       tuple_xy = _getTerminalSize_windows()
       if tuple_xy is None:
          tuple_xy = _getTerminalSize_tput()
          # needed for window's python in cygwin's xterm!
   if current_os == 'Linux' or current_os == 'Darwin' or  current_os.startswith('CYGWIN'):
       tuple_xy = _getTerminalSize_linux()
   if tuple_xy is None:
       print "default"
       tuple_xy = (80, 25)      # default value
   return tuple_xy

def _getTerminalSize_windows():
    res=None
    try:
        from ctypes import windll, create_string_buffer

        # stdin handle is -10
        # stdout handle is -11
        # stderr handle is -12

        h = windll.kernel32.GetStdHandle(-12)
        csbi = create_string_buffer(22)
        res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
    except:
        return None
    if res:
        import struct
        (bufx, bufy, curx, cury, wattr,
         left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
        sizex = right - left + 1
        sizey = bottom - top + 1
        return sizex, sizey
    else:
        return None

def _getTerminalSize_tput():
    # get terminal width
    # src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window
    try:
       import subprocess
       proc=subprocess.Popen(["tput", "cols"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
       output=proc.communicate(input=None)
       cols=int(output[0])
       proc=subprocess.Popen(["tput", "lines"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
       output=proc.communicate(input=None)
       rows=int(output[0])
       return (cols,rows)
    except:
       return None


def _getTerminalSize_linux():
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,'1234'))
        except:
            return None
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        try:
            cr = (env['LINES'], env['COLUMNS'])
        except:
            return None
    return int(cr[1]), int(cr[0])

if __name__ == "__main__":
    sizex,sizey=getTerminalSize()
    print  'width =',sizex,'height =',sizey

I searched around and found a solution for windows at :

http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/

and a solution for linux here.

So here is a version which works both on linux, os x and windows/cygwin :

""" getTerminalSize()
 - get width and height of console
 - works on linux,os x,windows,cygwin(windows)
"""

__all__=['getTerminalSize']


def getTerminalSize():
   import platform
   current_os = platform.system()
   tuple_xy=None
   if current_os == 'Windows':
       tuple_xy = _getTerminalSize_windows()
       if tuple_xy is None:
          tuple_xy = _getTerminalSize_tput()
          # needed for window's python in cygwin's xterm!
   if current_os == 'Linux' or current_os == 'Darwin' or  current_os.startswith('CYGWIN'):
       tuple_xy = _getTerminalSize_linux()
   if tuple_xy is None:
       print "default"
       tuple_xy = (80, 25)      # default value
   return tuple_xy

def _getTerminalSize_windows():
    res=None
    try:
        from ctypes import windll, create_string_buffer

        # stdin handle is -10
        # stdout handle is -11
        # stderr handle is -12

        h = windll.kernel32.GetStdHandle(-12)
        csbi = create_string_buffer(22)
        res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
    except:
        return None
    if res:
        import struct
        (bufx, bufy, curx, cury, wattr,
         left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
        sizex = right - left + 1
        sizey = bottom - top + 1
        return sizex, sizey
    else:
        return None

def _getTerminalSize_tput():
    # get terminal width
    # src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window
    try:
       import subprocess
       proc=subprocess.Popen(["tput", "cols"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
       output=proc.communicate(input=None)
       cols=int(output[0])
       proc=subprocess.Popen(["tput", "lines"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
       output=proc.communicate(input=None)
       rows=int(output[0])
       return (cols,rows)
    except:
       return None


def _getTerminalSize_linux():
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,'1234'))
        except:
            return None
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        try:
            cr = (env['LINES'], env['COLUMNS'])
        except:
            return None
    return int(cr[1]), int(cr[0])

if __name__ == "__main__":
    sizex,sizey=getTerminalSize()
    print  'width =',sizex,'height =',sizey

回答 5

要么是:

import os
columns, rows = os.get_terminal_size(0)
# or
import shutil
columns, rows = shutil.get_terminal_size()

shutil函数只是一个包装器,os可以捕获一些错误并设置后备功能,但是它有一个巨大的警告- 在管道传输时会中断!,这是一笔不小的数目。
要获得配管时的端子尺寸,请os.get_terminal_size(0)改用。

第一个参数0是指示应使用stdin文件描述符而不是默认stdout的参数。我们要使用stdin,因为stdout在被管道传输时会自行分离,在这种情况下会引发错误。

我试图弄清楚什么时候使用stdout代替stdin参数有意义,并且不知道为什么它是默认值。

It’s either:

import os
columns, rows = os.get_terminal_size(0)
# or
import shutil
columns, rows = shutil.get_terminal_size()

The shutil function is just a wrapper around os one that catches some errors and set up a fallback, however it has one huge caveat – it breaks when piping!, which is a pretty huge deal.
To get terminal size when piping use os.get_terminal_size(0) instead.

First argument 0 is an argument indicating that stdin file descriptor should be used instead of default stdout. We want to use stdin because stdout detaches itself when it is being piped which in this case raises an error.

I’ve tried to figure out when would it makes sense to use stdout instead of stdin argument and have no idea why it’s a default here.


回答 6

从Python 3.3开始,它很简单:https : //docs.python.org/3/library/os.html#querying-the-size-of-a-terminal

>>> import os
>>> ts = os.get_terminal_size()
>>> ts.lines
24
>>> ts.columns
80

Starting at Python 3.3 it is straight forward: https://docs.python.org/3/library/os.html#querying-the-size-of-a-terminal

>>> import os
>>> ts = os.get_terminal_size()
>>> ts.lines
24
>>> ts.columns
80

回答 7

该代码Johannes似乎有一些问题:

  • getTerminalSize 需要 import os
  • 是什么env?看起来像os.environ

另外,为什么要切换linescols返回之前?如果TIOCGWINSZ并且stty都说lines那么cols,我说就这样吧。在我注意到不一致之前,这使我困惑了10分钟。

Sridhar,通过管道输出时没有出现该错误。我很确定它会被try-except正确捕获。

pascal,"HHHH"在我的机器上"hh"不起作用,但是可以。我在查找该功能的文档时遇到了麻烦。看起来它与平台有关。

chochem,注册成立。

这是我的版本:

def getTerminalSize():
    """
    returns (lines:int, cols:int)
    """
    import os, struct
    def ioctl_GWINSZ(fd):
        import fcntl, termios
        return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))
    # try stdin, stdout, stderr
    for fd in (0, 1, 2):
        try:
            return ioctl_GWINSZ(fd)
        except:
            pass
    # try os.ctermid()
    try:
        fd = os.open(os.ctermid(), os.O_RDONLY)
        try:
            return ioctl_GWINSZ(fd)
        finally:
            os.close(fd)
    except:
        pass
    # try `stty size`
    try:
        return tuple(int(x) for x in os.popen("stty size", "r").read().split())
    except:
        pass
    # try environment variables
    try:
        return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS"))
    except:
        pass
    # i give up. return default.
    return (25, 80)

It looks like there are some problems with that code, Johannes:

  • getTerminalSize needs to import os
  • what is env? looks like os.environ.

Also, why switch lines and cols before returning? If TIOCGWINSZ and stty both say lines then cols, I say leave it that way. This confused me for a good 10 minutes before I noticed the inconsistency.

Sridhar, I didn’t get that error when I piped output. I’m pretty sure it’s being caught properly in the try-except.

pascal, "HHHH" doesn’t work on my machine, but "hh" does. I had trouble finding documentation for that function. It looks like it’s platform dependent.

chochem, incorporated.

Here’s my version:

def getTerminalSize():
    """
    returns (lines:int, cols:int)
    """
    import os, struct
    def ioctl_GWINSZ(fd):
        import fcntl, termios
        return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))
    # try stdin, stdout, stderr
    for fd in (0, 1, 2):
        try:
            return ioctl_GWINSZ(fd)
        except:
            pass
    # try os.ctermid()
    try:
        fd = os.open(os.ctermid(), os.O_RDONLY)
        try:
            return ioctl_GWINSZ(fd)
        finally:
            os.close(fd)
    except:
        pass
    # try `stty size`
    try:
        return tuple(int(x) for x in os.popen("stty size", "r").read().split())
    except:
        pass
    # try environment variables
    try:
        return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS"))
    except:
        pass
    # i give up. return default.
    return (25, 80)

回答 8

如果在调用此脚本时没有控制终端,则此处的许多Python 2实现将失败。您可以检查sys.stdout.isatty()来确定这是否实际上是一个终端,但这将排除一堆情况,因此我认为找出终端大小的最有效方法是使用内置的curses包。

import curses
w = curses.initscr()
height, width = w.getmaxyx()

Many of the Python 2 implementations here will fail if there is no controlling terminal when you call this script. You can check sys.stdout.isatty() to determine if this is in fact a terminal, but that will exclude a bunch of cases, so I believe the most pythonic way to figure out the terminal size is to use the builtin curses package.

import curses
w = curses.initscr()
height, width = w.getmaxyx()

回答 9

我正在尝试从此处调用的解决方案stty size

columns = int(subprocess.check_output(['stty', 'size']).split()[1])

但是,这对我来说失败了,因为我正在处理一个脚本,该脚本期望stdin上的重定向输入,并且stty在这种情况下会抱怨“ stdin不是终端”。

我能够使它像这样工作:

with open('/dev/tty') as tty:
    height, width = subprocess.check_output(['stty', 'size'], stdin=tty).split()

I was trying the solution from here that calls out to stty size:

columns = int(subprocess.check_output(['stty', 'size']).split()[1])

However this failed for me because I was working on a script that expects redirected input on stdin, and stty would complain that “stdin isn’t a terminal” in that case.

I was able to make it work like this:

with open('/dev/tty') as tty:
    height, width = subprocess.check_output(['stty', 'size'], stdin=tty).split()

回答 10

@reannual的答案很好用,但是有一个问题:os.popen 现在已弃用。该subprocess模块应改为使用,所以这里的@ reannual的代码,使用一个版本subprocess,直接回答了这个问题(通过直接向列宽为int

import subprocess

columns = int(subprocess.check_output(['stty', 'size']).split()[1])

在OS X 10.9上测试

@reannual’s answer works well, but there’s an issue with it: os.popen is now deprecated. The subprocess module should be used instead, so here’s a version of @reannual’s code that uses subprocess and directly answers the question (by giving the column width directly as an int:

import subprocess

columns = int(subprocess.check_output(['stty', 'size']).split()[1])

Tested on OS X 10.9


回答 11

尝试“祝福”

我一直在寻找同样的东西。它非常易于使用,并提供用于在终端上进行着色,样式和定位的工具。您所需要的很简单:

from blessings import Terminal

t = Terminal()

w = t.width
h = t.height

在Linux中像灵符一样工作。(我不确定MacOSX和Windows)

在此处下载和文档

或者您可以使用pip安装它:

pip install blessings

Try “blessings”

I was looking for the very same thing. It is very easy to use and offers tools for coloring, styling and positioning in the terminal. What you need is as easy as:

from blessings import Terminal

t = Terminal()

w = t.width
h = t.height

Works like a charm in Linux. (I’m not sure about MacOSX and Windows)

Download and documentation here

or you can install it with pip:

pip install blessings

回答 12

如果您使用的是Python 3.3或更高版本,建议您get_terminal_size()按照已推荐的内置方法进行操作。但是,如果您坚持使用较旧的版本,并希望通过一种简单的跨平台方法来执行此操作,则可以使用asciimatics。该软件包支持Python 2.7之前的版本,并使用与上面建议的选项类似的选项来获取当前的终端/控制台大小。

只需构造您的Screen类并使用该dimensions属性即可获取高度和宽度。它已被证明可以在Linux,OSX和Windows上运行。

哦,这里有完整的披露:我是作者,因此,如果您有任何疑问,请随时打开一个新期刊。

If you’re using Python 3.3 or above, I’d recommend the built-in get_terminal_size() as already recommended. However if you are stuck with an older version and want a simple, cross-platform way of doing this, you could use asciimatics. This package supports versions of Python back to 2.7 and uses similar options to those suggested above to get the current terminal/console size.

Simply construct your Screen class and use the dimensions property to get the height and width. This has been proven to work on Linux, OSX and Windows.

Oh – and full disclosure here: I am the author, so please feel free to open a new issue if you have any problems getting this to work.


回答 13

这是应该与Linux和Solaris兼容的版本。基于madchine的帖子和评论。需要子流程模块。

def termsize():
    导入shlex,子流程,重新
    输出= subprocess.check_output(shlex.split('/ bin / stty -a'))
    m = re.search('rows \ D +(?P \ d +); column \ D +(?P \ d +);',输出)
    如果m:
        返回m.group('rows'),m.group('columns')
    引发OSError('错误响应:%s'%(输出))
>>> termize()
(“ 40”,“ 100”)

Here is an version that should be Linux and Solaris compatible. Based on the posts and commments from madchine. Requires the subprocess module.

def termsize():
    import shlex, subprocess, re
    output = subprocess.check_output(shlex.split('/bin/stty -a'))
    m = re.search('rows\D+(?P\d+); columns\D+(?P\d+);', output)
    if m:
        return m.group('rows'), m.group('columns')
    raise OSError('Bad response: %s' % (output))
>>> termsize()
('40', '100')

如何终止以shell = True启动的python子进程

问题:如何终止以shell = True启动的python子进程

我正在使用以下命令启动子流程:

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

但是,当我尝试杀死使用:

p.terminate()

要么

p.kill()

该命令一直在后台运行,所以我想知道如何才能真正终止该过程。

请注意,当我使用以下命令运行命令时:

p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)

发出时,它确实成功终止p.terminate()

I’m launching a subprocess with the following command:

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

However, when I try to kill using:

p.terminate()

or

p.kill()

The command keeps running in the background, so I was wondering how can I actually terminate the process.

Note that when I run the command with:

p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)

It does terminate successfully when issuing the p.terminate().


回答 0

使用进程组,以便能够向中的所有进程发送信号。为此,您应该将会话ID附加到生成的子进程的父进程中,在您的情况下,这是一个外壳程序。这将使其成为流程的小组负责人。因此,现在,当信号发送到流程组负责人时,它便被传输到该组的所有子流程。

这是代码:

import os
import signal
import subprocess

# The os.setsid() is passed in the argument preexec_fn so
# it's run after the fork() and before  exec() to run the shell.
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE, 
                       shell=True, preexec_fn=os.setsid) 

os.killpg(os.getpgid(pro.pid), signal.SIGTERM)  # Send the signal to all the process groups

Use a process group so as to enable sending a signal to all the process in the groups. For that, you should attach a session id to the parent process of the spawned/child processes, which is a shell in your case. This will make it the group leader of the processes. So now, when a signal is sent to the process group leader, it’s transmitted to all of the child processes of this group.

Here’s the code:

import os
import signal
import subprocess

# The os.setsid() is passed in the argument preexec_fn so
# it's run after the fork() and before  exec() to run the shell.
pro = subprocess.Popen(cmd, stdout=subprocess.PIPE, 
                       shell=True, preexec_fn=os.setsid) 

os.killpg(os.getpgid(pro.pid), signal.SIGTERM)  # Send the signal to all the process groups

回答 1

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
p.kill()

p.kill()最终终止了shell进程,cmd并且仍在运行。

我通过以下方法找到了一个方便的解决方法:

p = subprocess.Popen("exec " + cmd, stdout=subprocess.PIPE, shell=True)

这将导致cmd继承shell进程,而不是让shell启动不会被杀死的子进程。 p.pid然后将是您的cmd进程的ID。

p.kill() 应该管用。

我不知道这会对您的管道产生什么影响。

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
p.kill()

p.kill() ends up killing the shell process and cmd is still running.

I found a convenient fix this by:

p = subprocess.Popen("exec " + cmd, stdout=subprocess.PIPE, shell=True)

This will cause cmd to inherit the shell process, instead of having the shell launch a child process, which does not get killed. p.pid will be the id of your cmd process then.

p.kill() should work.

I don’t know what effect this will have on your pipe though.


回答 2

如果可以使用psutil,则可以完美地工作:

import subprocess

import psutil


def kill(proc_pid):
    process = psutil.Process(proc_pid)
    for proc in process.children(recursive=True):
        proc.kill()
    process.kill()


proc = subprocess.Popen(["infinite_app", "param"], shell=True)
try:
    proc.wait(timeout=3)
except subprocess.TimeoutExpired:
    kill(proc.pid)

If you can use psutil, then this works perfectly:

import subprocess

import psutil


def kill(proc_pid):
    process = psutil.Process(proc_pid)
    for proc in process.children(recursive=True):
        proc.kill()
    process.kill()


proc = subprocess.Popen(["infinite_app", "param"], shell=True)
try:
    proc.wait(timeout=3)
except subprocess.TimeoutExpired:
    kill(proc.pid)

回答 3

我可以用

from subprocess import Popen

process = Popen(command, shell=True)
Popen("TASKKILL /F /PID {pid} /T".format(pid=process.pid))

它杀死了cmd.exe我给命令的程序。

(在Windows上)

I could do it using

from subprocess import Popen

process = Popen(command, shell=True)
Popen("TASKKILL /F /PID {pid} /T".format(pid=process.pid))

it killed the cmd.exe and the program that i gave the command for.

(On Windows)


回答 4

shell=Trueshell是子进程时,命令就是它的子进程。因此,任何SIGTERMSIGKILL将杀死外壳程序但不会杀死它的子进程的过程,我不记得有什么好方法。我能想到的最好方法是使用shell=False,否则当您杀死父shell进程时,它将留下一个已失效的shell进程。

When shell=True the shell is the child process, and the commands are its children. So any SIGTERM or SIGKILL will kill the shell but not its child processes, and I don’t remember a good way to do it. The best way I can think of is to use shell=False, otherwise when you kill the parent shell process, it will leave a defunct shell process.


回答 5

这些答案均不适合我,因此我留下了有效的代码。就我而言,即使在终止进程.kill()并获得.poll()返回代码后,进程也没有终止。

按照subprocess.Popen 文档

“ …为了正确清理行为良好的应用程序,应终止子进程并完成通信…”

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()

就我而言,我proc.communicate()在打电话后就错过了proc.kill()。这将清理进程stdin,stdout …,并终止进程。

None of this answers worked for me so Im leaving the code that did work. In my case even after killing the process with .kill() and getting a .poll() return code the process didn’t terminate.

Following the subprocess.Popen documentation:

“…in order to cleanup properly a well-behaved application should kill the child process and finish communication…”

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()

In my case I was missing the proc.communicate() after calling proc.kill(). This cleans the process stdin, stdout … and does terminate the process.


回答 6

正如Sai所说,shell是孩子,因此信号被它拦截了-我发现的最佳方法是使用shell = False并使用shlex拆分命令行:

if isinstance(command, unicode):
    cmd = command.encode('utf8')
args = shlex.split(cmd)

p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

然后p.kill()和p.terminate()应该可以按照您的期望工作。

As Sai said, the shell is the child, so signals are intercepted by it — best way I’ve found is to use shell=False and use shlex to split the command line:

if isinstance(command, unicode):
    cmd = command.encode('utf8')
args = shlex.split(cmd)

p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

Then p.kill() and p.terminate() should work how you expect.


回答 7

我觉得我们可以使用:

import os
import signal
import subprocess
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

os.killpg(os.getpgid(pro.pid), signal.SIGINT)

这不会杀死您的所有任务,但会杀死p.pid进程

what i feel like we could use:

import os
import signal
import subprocess
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

os.killpg(os.getpgid(pro.pid), signal.SIGINT)

this will not kill all your task but the process with the p.pid


回答 8

我知道这是一个古老的问题,但这可能会对寻求其他方法的人有所帮助。这就是我在Windows上用来杀死已调用进程的方法。

si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.call(["taskkill", "/IM", "robocopy.exe", "/T", "/F"], startupinfo=si)

/ IM是图像名称,如果需要,您也可以执行/ PID。/ T杀死进程以及子进程。/ F强制终止它。如我所设置的,si是如何执行此操作而不显示CMD窗口。此代码在python 3中使用。

I know this is an old question but this may help someone looking for a different method. This is what I use on windows to kill processes that I’ve called.

si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.call(["taskkill", "/IM", "robocopy.exe", "/T", "/F"], startupinfo=si)

/IM is the image name, you can also do /PID if you want. /T kills the process as well as the child processes. /F force terminates it. si, as I have it set, is how you do this without showing a CMD window. This code is used in python 3.


回答 9

将信号发送到组中的所有进程

    self.proc = Popen(commands, 
            stdout=PIPE, 
            stderr=STDOUT, 
            universal_newlines=True, 
            preexec_fn=os.setsid)

    os.killpg(os.getpgid(self.proc.pid), signal.SIGHUP)
    os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)

Send the signal to all the processes in group

    self.proc = Popen(commands, 
            stdout=PIPE, 
            stderr=STDOUT, 
            universal_newlines=True, 
            preexec_fn=os.setsid)

    os.killpg(os.getpgid(self.proc.pid), signal.SIGHUP)
    os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)

回答 10

我在这里没有看到此内容,因此我将其放在此处,以防有人需要。如果您要做的只是确保子流程成功终止,则可以将其放在上下文管理器中。例如,我希望我的标准打印机打印出图像,并使用上下文管理器确保子进程终止。

import subprocess

with open(filename,'rb') as f:
    img=f.read()
with subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE) as lpr:
    lpr.stdin.write(img)
print('Printed image...')

我相信这种方法也是跨平台的。

I have not seen this mentioned here, so I am putting it out there in case someone needs it. If all you want to do is to make sure that your subprocess terminates successfully, you could put it in a context manager. For example, I wanted my standard printer to print an out image and using the context manager ensured that the subprocess terminated.

import subprocess

with open(filename,'rb') as f:
    img=f.read()
with subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE) as lpr:
    lpr.stdin.write(img)
print('Printed image...')

I believe this method is also cross-platform.


UnicodeDecodeError:’utf8’编解码器无法解码字节0x9c

问题:UnicodeDecodeError:’utf8’编解码器无法解码字节0x9c

我有一个套接字服务器,应该从客户端接收UTF-8有效字符。

问题是某些客户端(主要是黑客)正在通过它发送所有错误的数据。

我可以轻松地区分真正的客户端,但是我会将所有发送的数据记录到文件中,以便以后进行分析。

有时我会得到这样的œ导致UnicodeDecodeError错误的字符。

我需要使字符串UTF-8带有或不带有这些字符。


更新:

对于我的特殊情况,套接字服务是MTA,因此我只希望接收ASCII命令,例如:

EHLO example.com
MAIL FROM: <john.doe@example.com>
...

我将所有这些都记录在JSON中。

然后,一些没有好主意的人决定出售各种垃圾。

这就是为什么对于我的特定情况,完全可以剥离非ASCII字符。

I have a socket server that is supposed to receive UTF-8 valid characters from clients.

The problem is some clients (mainly hackers) are sending all the wrong kind of data over it.

I can easily distinguish the genuine client, but I am logging to files all the data sent so I can analyze it later.

Sometimes I get characters like this œ that cause the UnicodeDecodeError error.

I need to be able to make the string UTF-8 with or without those characters.


Update:

For my particular case the socket service was an MTA and thus I only expect to receive ASCII commands such as:

EHLO example.com
MAIL FROM: <john.doe@example.com>
...

I was logging all of this in JSON.

Then some folks out there without good intentions decided to send all kind of junk.

That is why for my specific case it is perfectly OK to strip the non ASCII characters.


回答 0

http://docs.python.org/howto/unicode.html#the-unicode-type

str = unicode(str, errors='replace')

要么

str = unicode(str, errors='ignore')

注意: 这将删除(忽略)有问题的字符,并返回不包含这些字符的字符串。

对我而言,这是理想的情况,因为我将其用作针对非ASCII输入的保护,这是我的应用程序所不允许的。

或者:使用codecs模块中的open方法读取文件:

import codecs
with codecs.open(file_name, 'r', encoding='utf-8',
                 errors='ignore') as fdata:

http://docs.python.org/howto/unicode.html#the-unicode-type

str = unicode(str, errors='replace')

or

str = unicode(str, errors='ignore')

Note: This will strip out (ignore) the characters in question returning the string without them.

For me this is ideal case since I’m using it as protection against non-ASCII input which is not allowed by my application.

Alternatively: Use the open method from the codecs module to read in the file:

import codecs
with codecs.open(file_name, 'r', encoding='utf-8',
                 errors='ignore') as fdata:

回答 1

将引擎从C更改为Python确实帮了我大忙。

引擎是C:

pd.read_csv(gdp_path, sep='\t', engine='c')

‘utf-8’编解码器无法解码位置18的字节0x92:无效的起始字节

引擎是Python:

pd.read_csv(gdp_path, sep='\t', engine='python')

对我来说没有错误。

Changing the engine from C to Python did the trick for me.

Engine is C:

pd.read_csv(gdp_path, sep='\t', engine='c')

‘utf-8’ codec can’t decode byte 0x92 in position 18: invalid start byte

Engine is Python:

pd.read_csv(gdp_path, sep='\t', engine='python')

No errors for me.


回答 2

现在,我开始使用Python 3时,这种类型的问题就冒出来了。我不知道Python 2只是在蒸腾文件编码方面的任何问题。

在上述方法都不适合我之后,我找到了关于差异以及如何找到解决方案的很好的解释。

http://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html

简而言之,要使Python 3的行为与Python 2尽可能相似,请使用:

with open(filename, encoding="latin-1") as datafile:
    # work on datafile here

但是,请阅读文章,没有一种适合所有解决方案的尺寸。

This type of issue crops up for me now that I’ve moved to Python 3. I had no idea Python 2 was simply steam rolling any issues with file encoding.

I found this nice explanation of the differences and how to find a solution after none of the above worked for me.

http://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html

In short, to make Python 3 behave as similarly as possible to Python 2 use:

with open(filename, encoding="latin-1") as datafile:
    # work on datafile here

However, read the article, there is no one size fits all solution.


回答 3

>>> '\x9c'.decode('cp1252')
u'\u0153'
>>> print '\x9c'.decode('cp1252')
œ
>>> '\x9c'.decode('cp1252')
u'\u0153'
>>> print '\x9c'.decode('cp1252')
œ

回答 4

我有同样的问题,UnicodeDecodeError我用这条线解决了。不知道这是否是最好的方法,但是对我有用。

str = str.decode('unicode_escape').encode('utf-8')

I had same problem with UnicodeDecodeError and i solved it with this line. Don’t know if is the best way but it worked for me.

str = str.decode('unicode_escape').encode('utf-8')

回答 5

首先,使用get_encoding_type来获取编码的文件类型:

import os    
from chardet import detect

# get file encoding type
def get_encoding_type(file):
    with open(file, 'rb') as f:
        rawdata = f.read()
    return detect(rawdata)['encoding']

第二,打开以下类型的文件:

open(current_file, 'r', encoding = get_encoding_type, errors='ignore')

the first,Using get_encoding_type to get the files type of encode:

import os    
from chardet import detect

# get file encoding type
def get_encoding_type(file):
    with open(file, 'rb') as f:
        rawdata = f.read()
    return detect(rawdata)['encoding']

the second, opening the files with the type:

open(current_file, 'r', encoding = get_encoding_type, errors='ignore')

回答 6

万一有人有同样的问题。我将Vim与YouCompleteMe一起使用,无法通过此错误消息启动ycmd,我所做的是:export LC_CTYPE="en_US.UTF-8",问题消失了。

Just in case of someone has the same problem. I’am using vim with YouCompleteMe, failed to start ycmd with this error message, what I did is: export LC_CTYPE="en_US.UTF-8", the problem is gone.


回答 7

如果需要对文件进行更改但不知道文件的编码,该怎么办?如果您知道编码是ASCII兼容的,并且只想检查或修改ASCII部分,则可以使用surrogateescape错误处理程序打开文件:

with open(fname, 'r', encoding="ascii", errors="surrogateescape") as f:
    data = f.read()

What can you do if you need to make a change to a file, but don’t know the file’s encoding? If you know the encoding is ASCII-compatible and only want to examine or modify the ASCII parts, you can open the file with the surrogateescape error handler:

with open(fname, 'r', encoding="ascii", errors="surrogateescape") as f:
    data = f.read()

回答 8

我已经解决了这个问题,只需添加

df = pd.read_csv(fileName,encoding='latin1')

I have solved this problem just by adding

df = pd.read_csv(fileName,encoding='latin1')

安装mysqldb python接口时找不到mysql_config

问题:安装mysqldb python接口时找不到mysql_config

我正在尝试使Python脚本在通过ssh连接到的Linux服务器上运行。该脚本使用mysqldb。我有我需要的所有其他组件,但是当我尝试通过setuptools安装mySQLdb时,如下所示:

python setup.py install

我得到以下与mysql_config命令有关的错误报告。

sh: mysql_config: command not found
Traceback (most recent call last):
  File "setup.py", line 15, in <module>
    metadata, options = get_config()
  File "/usr/lib/python2.5/MySQL-python-1.2.3/setup_posix.py", line 43, in get_config
    libs = mysql_config("libs_r")
  File "/usr/lib/python2.5/MySQL-python-1.2.3/setup_posix.py", line 24, in mysql_config
    raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found

还有其他人遇到此错误吗?如果是,您如何解决该错误/我该怎么做才能成功安装mysqldb?

I am trying to get a Python script to run on the linux server I’m connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:,

python setup.py install

I get the following error report related to the mysql_config command.

sh: mysql_config: command not found
Traceback (most recent call last):
  File "setup.py", line 15, in <module>
    metadata, options = get_config()
  File "/usr/lib/python2.5/MySQL-python-1.2.3/setup_posix.py", line 43, in get_config
    libs = mysql_config("libs_r")
  File "/usr/lib/python2.5/MySQL-python-1.2.3/setup_posix.py", line 24, in mysql_config
    raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found

Has anyone else encountered this error and if so how did you resolve it/what can I do to successfully install mysqldb?


回答 0

mySQLdb是mysql的python接口,但不是mysql本身。显然,mySQLdb需要命令“ mysql_config”,因此您需要先安装该命令。

您可以通过从shell运行“ mysql”来确认自己是否安装了mysql吗?这应该给您一个响应,而不是“ mysql:not found”。

您使用的是哪个Linux发行版?Mysql已为大多数Linux发行版预先打包。例如,对于debian / ubuntu,安装mysql就像

sudo apt-get install mysql-server

mysql-config位于不同的软件包中,可以从安装(同样,假设debian / ubuntu):

sudo apt-get install libmysqlclient-dev

如果您使用的是mariadb,请替换为mysql,然后运行

sudo apt-get install libmariadbclient-dev

参考:https : //github.com/JudgeGirl/Judge-sender/issues/4#issuecomment-186542797

mySQLdb is a python interface for mysql, but it is not mysql itself. And apparently mySQLdb needs the command ‘mysql_config’, so you need to install that first.

Can you confirm that you did or did not install mysql itself, by running “mysql” from the shell? That should give you a response other than “mysql: command not found”.

Which linux distribution are you using? Mysql is pre-packaged for most linux distributions. For example, for debian / ubuntu, installing mysql is as easy as

sudo apt-get install mysql-server

mysql-config is in a different package, which can be installed from (again, assuming debian / ubuntu):

sudo apt-get install libmysqlclient-dev

if you are using mariadb, the drop in replacement for mysql, then run

sudo apt-get install libmariadbclient-dev

Reference: https://github.com/JudgeGirl/Judge-sender/issues/4#issuecomment-186542797


回答 1

我正在python-mysql使用以下命令在Ubuntu 12.04上安装

pip install mysql-python

首先,我有同样的问题:

Not Found "mysql_config"

这对我有用

$ sudo apt-get install libmysqlclient-dev

然后我有这个问题:

...
_mysql.c:29:20: error fatal: Python.h: No existe el archivo o el directorio

compilación terminada.

error: command 'gcc' failed with exit status 1

然后我尝试了

apt-get install python-dev

然后我很高兴:)

pip install mysql-python
    Installing collected packages: mysql-python
      Running setup.py install for mysql-python
        building '_mysql' extension
        gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,4,'beta',4) -D__version__=1.2.4b4 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g
        In file included from _mysql.c:44:0:
        /usr/include/mysql/my_config.h:422:0: aviso: se redefinió "HAVE_WCSCOLL" [activado por defecto]
        /usr/include/python2.7/pyconfig.h:890:0: nota: esta es la ubicación de la definición previa
        gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-x86_64-2.7/_mysql.o -L/usr/lib/x86_64-linux-gnu -lmysqlclient_r -lpthread -lz -lm -lrt -ldl -o build/lib.linux-x86_64-2.7/_mysql.so

Successfully installed mysql-python
Cleaning up...

I was installing python-mysql on Ubuntu 12.04 using

pip install mysql-python

First I had the same problem:

Not Found "mysql_config"

This worked for me

$ sudo apt-get install libmysqlclient-dev

Then I had this problem:

...
_mysql.c:29:20: error fatal: Python.h: No existe el archivo o el directorio

compilación terminada.

error: command 'gcc' failed with exit status 1

Then I tried with

apt-get install python-dev

And then I was happy :)

pip install mysql-python
    Installing collected packages: mysql-python
      Running setup.py install for mysql-python
        building '_mysql' extension
        gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,4,'beta',4) -D__version__=1.2.4b4 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g
        In file included from _mysql.c:44:0:
        /usr/include/mysql/my_config.h:422:0: aviso: se redefinió "HAVE_WCSCOLL" [activado por defecto]
        /usr/include/python2.7/pyconfig.h:890:0: nota: esta es la ubicación de la definición previa
        gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-x86_64-2.7/_mysql.o -L/usr/lib/x86_64-linux-gnu -lmysqlclient_r -lpthread -lz -lm -lrt -ldl -o build/lib.linux-x86_64-2.7/_mysql.so

Successfully installed mysql-python
Cleaning up...

回答 2

(特定于Mac OS X)

我做了很多尝试,但是这些命令最终对我有用。

  1. 安装 mysql
    brew install mysql
  2. brew unlink mysql
  3. brew install mysql-connector-c
  4. 将mysql bin文件夹添加到PATH
    export PATH=/usr/local/Cellar/mysql/8.0.11/bin:$PATH
  5. mkdir /usr/local/Cellar/lib/
  6. 创建一个符号链接
    sudo ln -s /usr/local/Cellar/mysql/8.0.11/lib/libmysqlclient.21.dylib /usr/local/Cellar/lib/libmysqlclient.21.dylib
  7. brew reinstall openssl来源
  8. 最后,安装mysql-client
    LIBRARY_PATH=$LIBRARY_PATH:/usr/local/opt/openssl/lib/ pip install mysqlclient

更新:如果此方法不起作用,@ vinyll建议brew link mysql在步骤8之前运行。

(Specific to Mac OS X)

I have tried a lot of things, but these set of commands finally worked for me.

  1. Install mysql
    brew install mysql
    
  2. brew unlink mysql
  3. brew install mysql-connector-c
  4. Add the mysql bin folder to PATH
    export PATH=/usr/local/Cellar/mysql/8.0.11/bin:$PATH
    
  5. mkdir /usr/local/Cellar/lib/
  6. Create a symlink
    sudo ln -s /usr/local/Cellar/mysql/8.0.11/lib/libmysqlclient.21.dylib /usr/local/Cellar/lib/libmysqlclient.21.dylib
    
  7. brew reinstall openssl (source)
  8. Finally, install mysql-client
    LIBRARY_PATH=$LIBRARY_PATH:/usr/local/opt/openssl/lib/ pip install mysqlclient
    

Update: In case this doesn’t work, @vinyll suggests to run brew link mysql before step 8.


回答 3

在红帽上,我不得不做

sudo yum install mysql-devel gcc gcc-devel python-devel
sudo easy_install mysql-python

然后它起作用了。

On Red Hat I had to do

sudo yum install mysql-devel gcc gcc-devel python-devel
sudo easy_install mysql-python

Then it worked.


回答 4

以下内容适用于Ubuntu 12.04 LTS:

apt-get install libmysqlclient-dev python-dev

尽管一切正常,但我仍然继续执行以下操作:

export PATH=$PATH:/usr/local/mysql/bin/

The below worked for me on Ubuntu 12.04 LTS:

apt-get install libmysqlclient-dev python-dev

All though it worked, i still went ahead to do the below:

export PATH=$PATH:/usr/local/mysql/bin/

回答 5

尝试安装时出现相同的错误mysql-python

这就是我修复它的方式。

sudo PATH=/usr/local/mysql/bin/:$PATH pip install mysql-python

问题是安装程序无法在默认路径中找到mysql_config。现在它可以..并且有效..

 15 warnings generated.
    clang -bundle -undefined dynamic_lookup -Wl,-F. build/temp.macosx-10.8-intel-2.7/_mysql.o -L/usr/local/mysql/lib -lmysqlclient_r -lz -lm -lmygcc -o build/lib.macosx-10.8-intel-2.7/_mysql.so -arch x86_64

Successfully installed mysql-python
Cleaning up...

希望这可以帮助。

谢谢。

I got the same error while trying to install mysql-python.

This is how I fixed it.

sudo PATH=/usr/local/mysql/bin/:$PATH pip install mysql-python

The problem was that the installer could not find the mysql_config in the default path. Now it can ..and it worked..

 15 warnings generated.
    clang -bundle -undefined dynamic_lookup -Wl,-F. build/temp.macosx-10.8-intel-2.7/_mysql.o -L/usr/local/mysql/lib -lmysqlclient_r -lz -lm -lmygcc -o build/lib.macosx-10.8-intel-2.7/_mysql.so -arch x86_64

Successfully installed mysql-python
Cleaning up...

Hope this helps.

Thanks.


回答 6

我通过以下步骤解决了此问题:

sudo apt-get install libmysqlclient-dev
sudo apt-get install python-dev
sudo python setup.py install

I fixed this problem with the following steps:

sudo apt-get install libmysqlclient-dev
sudo apt-get install python-dev
sudo python setup.py install

回答 7

命令(也是mysql)mPATH可能丢失。

export PATH=$PATH:/usr/local/mysql/bin/

The commands (mysql too) mPATH might be missing.

export PATH=$PATH:/usr/local/mysql/bin/


回答 8

步骤1:-同时安装Python3和Python3-dev

sudo apt-get install python3 python3-dev

步骤2:- 安装Python和Mysql连接器

sudo apt-get install libmysqlclient-dev

步骤3:- 安装python mysql客户端

sudo apt-get install mysqlclient

这将解决您的问题

Step1:-Install Python3 & Python3-dev Both

sudo apt-get install python3 python3-dev

Step2:- Install Python & Mysql Connector

sudo apt-get install libmysqlclient-dev

step3:- Install python mysql client

sudo apt-get install mysqlclient

This will Solve your Problem


回答 9

如果您使用的是macOS,并且已经通过brew install安装了mysql@5.7,请执行以下操作:

  1. brew install mysql-connector-c
  2. brew unlink mysql@5.7
  3. brew link --overwrite --dry-run mysql@5.7 首先,查看哪些符号链接被覆盖
  4. brew link --overwrite --force mysql@5.7 用mysql@5.7实际覆盖与mysql相关的符号链接
  5. pip install mysqlclient

If you’re on macOS and already installed mysql@5.7 via brew install:

  1. brew install mysql-connector-c
  2. brew unlink mysql@5.7
  3. brew link --overwrite --dry-run mysql@5.7 first, to see what symlinks are getting overwritten
  4. brew link --overwrite --force mysql@5.7 to actually overwrite mysql-related symlinks with mysql@5.7
  5. pip install mysqlclient

回答 10

我通过安装libmysqlclient来修复它:

sudo apt-get install libmysqlclient16-dev

I fixed it by installing libmysqlclient:

sudo apt-get install libmysqlclient16-dev

回答 11

MySQL-python软件包正在使用该mysql_config命令来了解mysql主机上的配置。您的主机没有该mysql_config命令。

来自dev.mysql.com的MySQL开发库程序包(MySQL-devel-xxx)提供了此命令以及MySQL-python程序包所需的库。MySQL-devel可在下载-社区服务器区域中找到这些软件包。MySQL开发库软件包名称MySQL-devel以MySQL版本和linux平台(例如MySQL-devel-5.5.24-1.linux2.6.x86_64.rpm)为基础,并有所不同。

注意,您不需要安装mysql服务器。

The MySQL-python package is using the mysql_config command to learn about the mysql configuration on your host. Your host does not have the mysql_config command.

The MySQL development libraries package (MySQL-devel-xxx) from dev.mysql.com provides this command and the libraries needed by the MySQL-python package. The MySQL-devel packages are found in the download – community server area. The MySQL development library package names start with MySQL-devel and vary based MySQL version and linux platform (e.g. MySQL-devel-5.5.24-1.linux2.6.x86_64.rpm.)

Note that you do not need to install mysql server.


回答 12

不建议使用libmysqlclient-dev软件包,因此请使用以下命令对其进行修复。

软件包libmysqlclient-dev不可用,但是由另一个软件包引用。这可能意味着该软件包已丢失,已被废弃或只能从其他来源获得

sudo apt-get install default-libmysqlclient-dev

The package libmysqlclient-dev is deprecated, so use the below command to fix it.

Package libmysqlclient-dev is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source

sudo apt-get install default-libmysqlclient-dev

回答 13

在centos 7中,这对我有用:

yum install mariadb-devel
pip install mysqlclient

In centos 7 this works for me :

yum install mariadb-devel
pip install mysqlclient

回答 14

在我的Fedora 23机器上,我必须运行以下命令:

sudo dnf install mysql-devel

On my Fedora 23 machine I had to run the following:

sudo dnf install mysql-devel

回答 15

对于Alpine Linux:

$ apk add mariadb-dev mariadb-client mariadb-libs

MariaDB是MySQL的直接替代品,并成为Alpine 3.2的新标准。参见https://bugs.alpinelinux.org/issues/4264

For Alpine Linux:

$ apk add mariadb-dev mariadb-client mariadb-libs

MariaDB is a drop-in replacement for MySQL and became the new standard as of Alpine 3.2. See https://bugs.alpinelinux.org/issues/4264


回答 16

我认为,以下几行可以在终端上执行

 sudo ln -s /usr/local/zend/mysql/bin/mysql_config /usr/sbin/

该mysql_config目录用于MacOSx上的zend服务器。您可以像下面的几行一样在linux上做

sudo ln -s /usr/local/mysql/bin/mysql_config /usr/sbin/

这是默认的Linux mysql目录。

I think, following lines can be executed on terminal

 sudo ln -s /usr/local/zend/mysql/bin/mysql_config /usr/sbin/

This mysql_config directory is for zend server on MacOSx. You can do it for linux like following lines

sudo ln -s /usr/local/mysql/bin/mysql_config /usr/sbin/

This is default linux mysql directory.


回答 17

我遇到了这个问题,并通过将符号链接添加到来解决mysql_config

我已经用自制软件安装了mysql,并在输出中看到了这一点。

Error: The `brew link` step did not complete successfully

根据您的购买方式,mysql它会出现在不同的地方。以我为例,/usr/local/Cellar/mysql
一旦您知道它在哪里,就应该可以建立一个指向python寻找位置的符号链接。 /usr/local/mysql

这对我有用。

ln -s /usr/local/Cellar/mysql/<< VERSION >>/bin/mysql_config   /usr/local/mysql/bin/mysql_config

I had this issues and solved if by adding a symlink to mysql_config.

I had installed mysql with homebrew and saw this in the output.

Error: The `brew link` step did not complete successfully

Depending on how you got mysql it will be in different places. In my case /usr/local/Cellar/mysql
Once you know where it is you should be able to ma a symbolic link to where python is looking for it. /usr/local/mysql

This worked for me.

ln -s /usr/local/Cellar/mysql/<< VERSION >>/bin/mysql_config   /usr/local/mysql/bin/mysql_config

回答 18

我有同样的问题。我通过按照本教程在Ubuntu 16.04上使用python3-dev安装Python的方式解决了问题:

sudo apt-get update
sudo apt-get -y upgrade
sudo apt-get install -y python3-pip
sudo apt-get install build-essential libssl-dev libffi-dev python3-dev

现在您可以设置虚拟环境:

sudo apt-get install -y python3-venv
pyvenv my_env
source my_env/bin/activate

I had the same problem. I solved it by following this tutorial to install Python with python3-dev on Ubuntu 16.04:

sudo apt-get update
sudo apt-get -y upgrade
sudo apt-get install -y python3-pip
sudo apt-get install build-essential libssl-dev libffi-dev python3-dev

And now you can set up your virtual environment:

sudo apt-get install -y python3-venv
pyvenv my_env
source my_env/bin/activate

回答 19

您需要安装python-dev软件包:

sudo apt-get install python-dev

You need to install the python-dev package:

sudo apt-get install python-dev

回答 20

须藤apt-get install python-mysqldb

Python 2.5?听起来您正在使用非常旧的Ubuntu Server版本(Hardy 8.04?)-请确认服务器使用的Linux版本。

在ubuntu软件包数据库上搜索python-mysql

一些其他信息:

从mysql-python的自述文件-

红帽Linux ………….

MySQL-python已预包装在Red Hat Linux 7.x和更高版本中。这包括Fedora Core和Red Hat Enterprise Linux。您还可以如上所述构建自己的RPM软件包。

Debian GNU / Linux …………….

打包为python-mysqldb_ ::

# apt-get install python-mysqldb

或使用Synaptic。

.. _ python-mysqldbhttp : //packages.debian.org/python-mysqldb

Ubuntu ……

与Debian相同。

脚注:如果您确实使用的服务器发行版早于Ubuntu 10.04,则您不受官方支持,因此应尽快升级。

sudo apt-get install python-mysqldb

Python 2.5? Sounds like you are using a very old version of Ubuntu Server (Hardy 8.04?) – please confirm which Linux version the server uses.

python-mysql search on ubuntu package database

Some additional info:

From the README of mysql-python –

Red Hat Linux ………….

MySQL-python is pre-packaged in Red Hat Linux 7.x and newer. This includes Fedora Core and Red Hat Enterprise Linux. You can also build your own RPM packages as described above.

Debian GNU/Linux …………….

Packaged as python-mysqldb_::

# apt-get install python-mysqldb

Or use Synaptic.

.. _python-mysqldb: http://packages.debian.org/python-mysqldb

Ubuntu ……

Same as with Debian.

Footnote: If you really are using a server distribution older than Ubuntu 10.04 then you are out of official support, and should upgrade sooner rather than later.


回答 21

该方法仅适用于那些知道已安装Mysql但仍找不到mysql_config的用户。如果python安装无法在系统路径中找到mysql_config,则会发生这种情况,如果通过.dmg Mac Package完成安装或在某个自定义路径中进行安装,则通常会发生这种情况。MySqlDB最简单且记录在案的方法是更改site.cfg。找到可能位于/ usr / local / mysql / bin /中的mysql_config,然后像下面那样更改变量mysql_config,然后再次运行安装。不要忘记通过删除“#”取消注释

在行下更改

“ #mysql_config = / usr / local / bin / mysql_config”

“ mysql_config = / usr / local / mysql / bin / mysql_config”

取决于系统中的路径。

顺便说一句,我在更改site.cfg之后使用python安装

sudo /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python setup.py安装

This method is only for those who know that Mysql is installed but still mysql_config can’t be find. This happens if python install can’t find mysql_config in your system path, which mostly happens if you have done the installation via .dmg Mac Package or installed at some custom path. The easiest and documented way by MySqlDB is to change the site.cfg. Find the mysql_config which is probably in /usr/local/mysql/bin/ and change the variable namely mysql_config just like below and run the installation again. Don’t forget to un-comment it by removing “#”

Change below line

“#mysql_config = /usr/local/bin/mysql_config”

to

“mysql_config = /usr/local/mysql/bin/mysql_config”

depending upon the path in your system.

By the way I used python install after changing the site.cfg

sudo /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python setup.py install


回答 22

到目前为止,所有解决方案(Linux)都需要具有sudoroot用户权限才能安装。如果您没有root权限且没有root权限,则这是一个解决方案sudo。(否sudo apt install ...):

  1. 从此镜像下载libmysqlclient-dev的.deb文件
  2. 导航到下载的文件并运行。dpkg -x libmysqlclient-dev_<version tag>.deb .这将提取一个名为的文件夹usr
  3. 符号链接./usr/bin/mysql_config到您的上找到的某个位置$PATH

    ln -s `pwd` /usr/bin/mysql_config FOLDER_IN_YOUR_PATH

  4. 现在应该可以找到 mysql_config

在Ubuntu 18.04上测试。

So far, all solutions (Linux) require sudo or root rights to install . Here is a solution if you do not have root rights and without sudo. (no sudo apt install ...):

  1. Download the .deb file of the libmysqlclient-dev, e.g. from this mirror
  2. Navigate to the downloaded file and run dpkg -x libmysqlclient-dev_<version tag>.deb . This will extract a folder called usr.
  3. Symlink ./usr/bin/mysql_config to somewhere that is found on your $PATH:

    ln -s `pwd` /usr/bin/mysql_config FOLDER_IN_YOUR_PATH

  4. It should now be able to find mysql_config

Tested on Ubuntu 18.04.


回答 23

对于macOS Mojave,需要附加配置,编译器才能找到openssl,您可能需要设置:

export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"

For macOS Mojave , additional configuration was required, for compilers to find openssl you may need to set:

export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"

回答 24

我认为在2020年解决此问题的最便捷方法是使用另一个python软件包。我们不需要安装任何其他二进制软件。

尝试这个

pip install mysql-connector-python

然后

import mysql.connector

mydb = mysql.connector.connect(
          host="",
          user="",
          passwd="",
          database=""
          )      
cursor = mydb.cursor( buffered=True)
cursor.execute('show tables;')
cursor.execute('insert into test values (null, "a",10)')
mydb.commit()
mydb.disconnect()

I think the most convenient way to solve this problem in 2020 is using another python package. We don’t need install any other binary software.

Try this

pip install mysql-connector-python

and then

import mysql.connector

mydb = mysql.connector.connect(
          host="",
          user="",
          passwd="",
          database=""
          )      
cursor = mydb.cursor( buffered=True)
cursor.execute('show tables;')
cursor.execute('insert into test values (null, "a",10)')
mydb.commit()
mydb.disconnect()

回答 25

我遇到了同样的问题,只是将* mysql_config *所在的路径添加到环境变量PATH中,它对我有用。

I encountered the same problem, just added the path where *mysql_config* resided to the environment variable PATH and it worked for me.


回答 26

sudo apt-get build-dep python-mysqldb 将安装所有依赖项以从PIP / easy_install构建软件包

sudo apt-get build-dep python-mysqldb will install all the dependencies to build the package from PIP/easy_install


回答 27

由于实际错误是

gcc ... -I/usr/include/python2.7 ...

_mysql.c:29:20: error: Python.h: No such file or directory

并且如果您无法安装python-dev或python-devel软件包,则可以从http://hg.python.org/下载包含所需版本的python源的存档,并将标头文件放置在正确的文件夹中,以包含

As actual error is

gcc ... -I/usr/include/python2.7 ...

_mysql.c:29:20: error: Python.h: No such file or directory

and If you can’t install python-dev or python-devel packages, you may download archive with needed version of python sources from http://hg.python.org/ and place headers files in proper folder for include


回答 28

只需输入:

$ sudo apt-get install python-dev
$ venv/bin/pip install MySQL-python

这样可以解决这个问题。

Just type:

$ sudo apt-get install python-dev
$ venv/bin/pip install MySQL-python

This will solve this problems.


回答 29

在CentOS 7中,应执行以下操作:

#step1:install mysql 
https://dev.mysql.com/doc/mysql-yum-repo-quick-guide/en/

#step2:
sudo yum install mysql-devel

In CentOS 7 , the following things should be done:

#step1:install mysql 
https://dev.mysql.com/doc/mysql-yum-repo-quick-guide/en/

#step2:
sudo yum install mysql-devel

如果不存在,Python中的open()不会创建文件

问题:如果不存在,Python中的open()不会创建文件

如果文件以读/写方式打开,或者以不存在的方式创建,然后以读/写方式打开,最好的方法是什么?根据我的阅读,file = open('myfile.dat', 'rw')应该这样做吗?

它对我不起作用(Python 2.6.2),我想知道这是否是版本问题,或者不应该那样工作或做什么。

最重要的是,我只需要解决这个问题。我对其他东西很好奇,但是我所需要的只是做开始部分的好方法。

封闭目录可由用户和组而非其他用户(我在Linux系统上…因此权限775)可写,确切的错误是:

IOError:没有这样的文件或目录。

What is the best way to open a file as read/write if it exists, or if it does not, then create it and open it as read/write? From what I read, file = open('myfile.dat', 'rw') should do this, right?

It is not working for me (Python 2.6.2) and I’m wondering if it is a version problem, or not supposed to work like that or what.

The bottom line is, I just need a solution for the problem. I am curious about the other stuff, but all I need is a nice way to do the opening part.

The enclosing directory was writeable by user and group, not other (I’m on a Linux system… so permissions 775 in other words), and the exact error was:

IOError: no such file or directory.


回答 0

您应该使用open以下w+模式:

file = open('myfile.dat', 'w+')

You should use open with the w+ mode:

file = open('myfile.dat', 'w+')

回答 1

以下方法的优点是,即使在途中引发了异常,文件也会在块的末尾正确关闭。它等效于try-finally,但要短得多。

with open("file.dat","a+") as f:
    f.write(...)
    ...

a +打开一个文件以进行附加和读取。如果文件存在,则文件指针位于文件的末尾。该文件以追加模式打开。如果该文件不存在,它将创建一个用于读取和写入的新文件。- Python的文件模式

seek()方法设置文件的当前位置。

f.seek(pos [, (0|1|2)])
pos .. position of the r/w pointer
[] .. optionally
() .. one of ->
  0 .. absolute position
  1 .. relative position to current
  2 .. relative position from end

只允许使用“ rwab +”字符;必须完全是“ rwa”之一-请参阅Stack Overflow问题Python文件模式详细信息

The advantage of the following approach is that the file is properly closed at the block’s end, even if an exception is raised on the way. It’s equivalent to try-finally, but much shorter.

with open("file.dat","a+") as f:
    f.write(...)
    ...

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. –Python file modes

seek() method sets the file’s current position.

f.seek(pos [, (0|1|2)])
pos .. position of the r/w pointer
[] .. optionally
() .. one of ->
  0 .. absolute position
  1 .. relative position to current
  2 .. relative position from end

Only “rwab+” characters are allowed; there must be exactly one of “rwa” – see Stack Overflow question Python file modes detail.


回答 2

好的做法是使用以下方法:

import os

writepath = 'some/path/to/file.txt'

mode = 'a' if os.path.exists(writepath) else 'w'
with open(writepath, mode) as f:
    f.write('Hello, world!\n')

Good practice is to use the following:

import os

writepath = 'some/path/to/file.txt'

mode = 'a' if os.path.exists(writepath) else 'w'
with open(writepath, mode) as f:
    f.write('Hello, world!\n')

回答 3

将“ rw”更改为“ w +”

或使用“ a +”进行附加(不删除现有内容)

Change “rw” to “w+”

Or use ‘a+’ for appending (not erasing existing content)


回答 4

>>> import os
>>> if os.path.exists("myfile.dat"):
...     f = file("myfile.dat", "r+")
... else:
...     f = file("myfile.dat", "w")

r +表示读/写

>>> import os
>>> if os.path.exists("myfile.dat"):
...     f = file("myfile.dat", "r+")
... else:
...     f = file("myfile.dat", "w")

r+ means read/write


回答 5

从python 3.4开始,您应该使用pathlib“触摸”文件。
与该线程中提出的解决方案相比,这是一种更为优雅的解决方案。

from pathlib import Path

filename = Path('myfile.txt')
filename.touch(exist_ok=True)  # will create file, if it exists will do nothing
file = open(filename)

与目录相同:

filename.mkdir(parents=True, exist_ok=True)

Since python 3.4 you should use pathlib to “touch” files.
It is a much more elegant solution than the proposed ones in this thread.

from pathlib import Path

filename = Path('myfile.txt')
filename.touch(exist_ok=True)  # will create file, if it exists will do nothing
file = open(filename)

Same thing with directories:

filename.mkdir(parents=True, exist_ok=True)

回答 6

我的答案:

file_path = 'myfile.dat'
try:
    fp = open(file_path)
except IOError:
    # If not exists, create the file
    fp = open(file_path, 'w+')

My answer:

file_path = 'myfile.dat'
try:
    fp = open(file_path)
except IOError:
    # If not exists, create the file
    fp = open(file_path, 'w+')

回答 7

'''
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in write mode
r+  open for reading and writing. Does not create file.
a+  create file if it doesn't exist and open it in append mode
'''

例:

file_name = 'my_file.txt'
f = open(file_name, 'w+')  # open file in write mode
f.write('python rules')
f.close()

我希望这有帮助。[仅供参考,请使用python 3.6.2版]

'''
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in write mode
r+  open for reading and writing. Does not create file.
a+  create file if it doesn't exist and open it in append mode
'''

example:

file_name = 'my_file.txt'
f = open(file_name, 'w+')  # open file in write mode
f.write('python rules')
f.close()

I hope this helps. [FYI am using python version 3.6.2]


回答 8

open('myfile.dat', 'a') 为我工作,就好。

在py3k中,您的代码将引发ValueError

>>> open('myfile.dat', 'rw')
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    open('myfile.dat', 'rw')
ValueError: must have exactly one of read/write/append mode

在python-2.6中它引发了IOError

open('myfile.dat', 'a') works for me, just fine.

in py3k your code raises ValueError:

>>> open('myfile.dat', 'rw')
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    open('myfile.dat', 'rw')
ValueError: must have exactly one of read/write/append mode

in python-2.6 it raises IOError.


回答 9

采用:

import os

f_loc = r"C:\Users\Russell\Desktop\myfile.dat"

# Create the file if it does not exist
if not os.path.exists(f_loc):
    open(f_loc, 'w').close()

# Open the file for appending and reading
with open(f_loc, 'a+') as f:
    #Do stuff

注意:打开文件后必须将其关闭,with上下文管理器是让Python为您解决此问题的一种好方法。

Use:

import os

f_loc = r"C:\Users\Russell\Desktop\myfile.dat"

# Create the file if it does not exist
if not os.path.exists(f_loc):
    open(f_loc, 'w').close()

# Open the file for appending and reading
with open(f_loc, 'a+') as f:
    #Do stuff

Note: Files have to be closed after you open them, and the with context manager is a nice way of letting Python take care of this for you.


回答 10

您想对文件做什么?只写它还是读和写?

'w''a'将允许写入,如果文件不存在,则会创建该文件。

如果需要读取文件,则在打开文件之前必须先将其存在。您可以在打开它之前测试它的存在或使用try / except。

What do you want to do with file? Only writing to it or both read and write?

'w', 'a' will allow write and will create the file if it doesn’t exist.

If you need to read from a file, the file has to be exist before open it. You can test its existence before opening it or use a try/except.


回答 11

我认为r+不是rw。我只是一个入门者,这就是我在文档中看到的内容。

I think it’s r+, not rw. I’m just a starter, and that’s what I’ve seen in the documentation.


回答 12

使用w +写入文件,如果存在则截断,使用r +读取文件,如果文件不存在则创建一个,但不写入(并返回null),或者使用a +创建新文件或追加到现有文件。

Put w+ for writing the file, truncating if it exist, r+ to read the file, creating one if it don’t exist but not writing (and returning null) or a+ for creating a new file or appending to a existing one.


回答 13

因此,您想将数据写入文件,但前提是该文件尚不存在?

通过使用鲜为人知的x模式open()而不是通常的w模式,可以轻松解决此问题。例如:

 >>> with open('somefile', 'wt') as f:
 ...     f.write('Hello\n')
...
>>> with open('somefile', 'xt') as f:
...     f.write('Hello\n')
...
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'somefile'
  >>>

如果文件是二进制模式,请使用模式xb而不是xt。

So You want to write data to a file, but only if it doesn’t already exist?.

This problem is easily solved by using the little-known x mode to open() instead of the usual w mode. For example:

 >>> with open('somefile', 'wt') as f:
 ...     f.write('Hello\n')
...
>>> with open('somefile', 'xt') as f:
...     f.write('Hello\n')
...
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
FileExistsError: [Errno 17] File exists: 'somefile'
  >>>

If the file is binary mode, use mode xb instead of xt.


回答 14

如果您想打开它进行读写,那么我假设您不想在打开文件时截断它,并且希望在打开文件后立即读取文件。所以这是我正在使用的解决方案:

file = open('myfile.dat', 'a+')
file.seek(0, 0)

If you want to open it to read and write, I’m assuming you don’t want to truncate it as you open it and you want to be able to read the file right after opening it. So this is the solution I’m using:

file = open('myfile.dat', 'a+')
file.seek(0, 0)

回答 15

也许这会有所帮助

首先将os模块导入py文件

import os

然后创建一个名为save_file的变量并将其设置为您要制作html或txt的文件,在这种情况下,将其设置为txt文件

save_file = "history.txt"

然后定义一个函数,该函数将使用os.path.is file方法检查文件是否存在,如果不存在,它将创建一个文件

def check_into():
if os.path.isfile(save_file):
    print("history file exists..... \nusing for writting....")
else:
    print("history file not exists..... \ncreating it..... ")
    file = open(save_file, 'w')
    time.sleep(2)
    print('file created ')
    file.close()

最后调用函数

check_into()

may be this will help

first import os module into your py file

import os

then create a variable named save_file and set it to file you want to make html or txt in this case a txt file

save_file = "history.txt"

then define a function that will use os.path.is file method to check if file exist and if not it will create a file

def check_into():
if os.path.isfile(save_file):
    print("history file exists..... \nusing for writting....")
else:
    print("history file not exists..... \ncreating it..... ")
    file = open(save_file, 'w')
    time.sleep(2)
    print('file created ')
    file.close()

and at last call the function

check_into()

回答 16

import os, platform
os.chdir('c:\\Users\\MS\\Desktop')

try :
    file = open("Learn Python.txt","a")
    print('this file is exist')
except:
    print('this file is not exist')
file.write('\n''Hello Ashok')

fhead = open('Learn Python.txt')

for line in fhead:

    words = line.split()
print(words)
import os, platform
os.chdir('c:\\Users\\MS\\Desktop')

try :
    file = open("Learn Python.txt","a")
    print('this file is exist')
except:
    print('this file is not exist')
file.write('\n''Hello Ashok')

fhead = open('Learn Python.txt')

for line in fhead:

    words = line.split()
print(words)

Gitsome-增强型Git/GitHub命令行界面(CLI)。GitHub和GitHub企业的官方集成:https://github.com/works-with/category/desktop-tools

一个Official Integration对于GitHub和GitHub Enterprise

为什么gitsome

Git命令行

虽然标准的Git命令行是管理基于Git的repo的一个很好的工具,但是它可以很难记住这个用法地址为:

  • 150多个瓷器和管道命令
  • 无数特定于命令的选项
  • 标签和分支等资源

Git命令行不与GitHub集成,强制您在命令行和浏览器之间切换

gitsome-具有自动完成功能的增压Git/GitHub CLI

gitsome旨在通过专注于以下方面来增强您的标准git/shell界面:

  • 提高易用性
  • 提高工作效率

深度GitHub集成

并不是所有的GitHub工作流都能在终端中很好地工作;gitsome试图将目标对准那些这样做的人

gitsome包括29个与一起使用的GitHub集成命令ALL外壳:

$ gh <command> [param] [options]

gh命令以及Git-Extrashub解锁更多GitHub集成的命令!

带有交互式帮助的Git和GitHub自动完成程序

您可以运行可选壳牌:

 $ gitsome

要启用自动完成交互式帮助对于以下内容:

通用自动补全程序

gitsome自动完成以下内容:

  • Shell命令
  • 文件和目录
  • 环境变量
  • 手册页
  • python

要启用其他自动完成,请查看Enabling Bash Completions部分

鱼式自动建议

gitsome支持鱼式自动建议。使用right arrow完成建议的关键

Python REPL

gitsome由以下人员提供动力xonsh,它支持Python REPL

在shell命令旁边运行Python命令:

附加内容xonsh功能可在xonsh tutorial

命令历史记录

gitsome跟踪您输入的命令并将其存储在~/.xonsh_history.json使用向上和向下箭头键循环查看命令历史记录

可自定义的突出显示

可以控制用于突出显示的ansi颜色,方法是更新~/.gitsomeconfig文件

颜色选项包括:

'black', 'red', 'green', 'yellow',
'blue', 'magenta', 'cyan', 'white'

对于无颜色,请将值设置为Nonewhite在某些终端上可能显示为浅灰色

可用的平台

gitsome适用于Mac、Linux、Unix、Windows,以及Docker

待办事项

并不是所有的GitHub工作流都能在终端中很好地工作;gitsome试图将目标对准那些这样做的人

  • 添加其他GitHub API集成

gitsome才刚刚开始。请随意……contribute!

索引

GitHub集成命令

安装和测试

杂项

GitHub集成命令语法

用法:

$ gh <command> [param] [options]

GitHub集成命令列表

  configure            Configure gitsome.
  create-comment       Create a comment on the given issue.
  create-issue         Create an issue.
  create-repo          Create a repo.
  emails               List all the user's registered emails.
  emojis               List all GitHub supported emojis.
  feed                 List all activity for the given user or repo.
  followers            List all followers and the total follower count.
  following            List all followed users and the total followed count.
  gitignore-template   Output the gitignore template for the given language.
  gitignore-templates  Output all supported gitignore templates.
  issue                Output detailed information about the given issue.
  issues               List all issues matching the filter.
  license              Output the license template for the given license.
  licenses             Output all supported license templates.
  me                   List information about the logged in user.
  notifications        List all notifications.
  octo                 Output an Easter egg or the given message from Octocat.
  pull-request         Output detailed information about the given pull request.
  pull-requests        List all pull requests.
  rate-limit           Output the rate limit.  Not available for Enterprise.
  repo                 Output detailed information about the given filter.
  repos                List all repos matching the given filter.
  search-issues        Search for all issues matching the given query.
  search-repos         Search for all repos matching the given query.
  starred              Output starred repos.
  trending             List trending repos for the given language.
  user                 List information about the given user.
  view                 View the given index in the terminal or a browser.

GitHub集成命令参考:COMMANDS.md

请参阅GitHub Integration Commands Reference in COMMANDS.md对于详细讨论所有GitHub集成命令、参数、选项和示例

请查看下一节,了解快速参考

GitHub集成命令快速参考

配置gitsome

要与GitHub正确集成,您必须首先配置gitsome

$ gh configure

对于GitHub Enterprise用户,使用-e/--enterprise标志:

$ gh configure -e

列表源

列出您的新闻源

$ gh feed

列出用户的活动摘要

查看您的活动订阅源或其他用户的活动订阅源,也可以选择使用寻呼机-p/--pager这个pager option可用于许多命令

$ gh feed donnemartin -p

列出回购的活动提要

$ gh feed donnemartin/gitsome -p

列出通知

$ gh notifications

列出拉式请求

查看您的回购的所有拉式请求:

$ gh pull-requests

过滤问题

查看您提到的所有未决问题:

$ gh issues --issue_state open --issue_filter mentioned

查看所有问题,只筛选分配给您的问题,而不考虑状态(打开、关闭):

$ gh issues --issue_state all --issue_filter assigned

有关过滤和州限定词的更多信息,请访问gh issues参考位置COMMANDS.md

过滤星级报告

$ gh starred "repo filter"

搜索问题和报告

搜索问题

+1最多的搜索问题:

$ gh search-issues "is:open is:issue sort:reactions-+1-desc" -p

评论最多的搜索问题:

$ gh search-issues "is:open is:issue sort:comments-desc" -p

使用“需要帮助”标签搜索问题:

$ gh search-issues "is:open is:issue label:\"help wanted\"" -p

已标记您的用户名的搜索问题@donnemartin

$ gh search-issues "is:issue donnemartin is:open" -p

搜索您所有未解决的私人问题:

$ gh search-issues "is:open is:issue is:private" -p

有关查询限定符的更多信息,请访问searching issues reference

搜索报告

搜索2015年或之后创建的所有Python repos,>=1000星:

$ gh search-repos "created:>=2015-01-01 stars:>=1000 language:python" --sort stars -p

有关查询限定符的更多信息,请访问searching repos reference

列出趋势报告和开发人员

查看趋势回购:

$ gh trending [language] [-w/--weekly] [-m/--monthly] [-d/--devs] [-b/--browser]

查看趋势DEV(目前仅浏览器支持DEV):

$ gh trending [language] --devs --browser

查看内容

这个view命令

查看前面列出的通知、拉取请求、问题、回复、用户等,HTML格式适合您的终端,也可以选择在您的浏览器中查看:

$ gh view [#] [-b/--browser]

这个issue命令

查看问题:

$ gh issue donnemartin/saws/1

这个pull-request命令

查看拉取请求:

$ gh pull-request donnemartin/awesome-aws/2

设置.gitignore

列出所有可用的.gitignore模板:

$ gh gitignore-templates

设置您的.gitignore

$ gh gitignore-template Python > .gitignore

设置LICENSE

列出所有可用的LICENSE模板:

$ gh licenses

设置您的或LICENSE

$ gh license MIT > LICENSE

召唤十月猫

在十月猫那天打电话说出给定的信息或复活节彩蛋:

$ gh octo [say]

查看配置文件

查看用户的配置文件

$ gh user octocat

查看您的个人资料

使用查看您的个人资料gh user [YOUR_USER_ID]命令或使用以下快捷方式:

$ gh me

创建评论、问题和报告

创建评论:

$ gh create-comment donnemartin/gitsome/1 -t "hello world"

创建问题:

$ gh create-issue donnemartin/gitsome -t "title" -b "body"

创建回购:

$ gh create-repo gitsome

选项:在寻呼机中查看

许多gh命令支持-p/--pager在寻呼机中显示结果的选项(如果可用)

用法:

$ gh <command> [param] [options] -p
$ gh <command> [param] [options] --pager

选项:在浏览器中查看

许多gh命令支持-b/--browser在默认浏览器(而不是终端)中显示结果的选项

用法:

$ gh <command> [param] [options] -b
$ gh <command> [param] [options] --browser

请参阅COMMANDS.md有关所有GitHub集成命令、参数、选项和示例的详细列表

记住这些命令有困难吗?看看手边的autocompleter with interactive help来指导您完成每个命令

注意,您可以将gitsome与其他实用程序(如Git-Extras

安装

PIP安装

gitsome托管在PyPI将安装以下命令gitsome

$ pip3 install gitsome

您还可以安装最新的gitsome来自GitHub源,可能包含尚未推送到PyPI的更改:

$ pip3 install git+https://github.com/donnemartin/gitsome.git

如果您没有安装在virtualenv,您可能需要运行sudo

$ sudo pip3 install gitsome

pip3

根据您的设置,您可能还希望运行pip3使用-H flag

$ sudo -H pip3 install gitsome

对于大多数Linux用户来说,pip3可以使用python3-pip套餐

例如,Ubuntu用户可以运行:

$ sudo apt-get install python3-pip

看这个ticket有关更多详细信息,请参阅

虚拟环境安装

您可以将Python包安装在virtualenv要避免依赖项或权限的潜在问题,请执行以下操作

如果您是Windows用户,或者如果您想了解更多有关virtualenv,看看这个guide

安装virtualenvvirtualenvwrapper

$ pip3 install virtualenv
$ pip3 install virtualenvwrapper
$ export WORKON_HOME=~/.virtualenvs
$ source /usr/local/bin/virtualenvwrapper.sh

创建gitsomevirtualenv并安装gitsome

$ mkvirtualenv gitsome
$ pip3 install gitsome

如果pip安装不起作用,您可能默认运行的是Python2。检查您正在运行的Python版本:

$ python --version

如果上面的调用结果是Python 2,请找到Python 3的路径:

$ which python3  # Python 3 path for mkvirtualenv's --python option

如果需要,安装Python 3。调用时设置Python版本mkvirtualenv

$ mkvirtualenv --python [Python 3 path from above] gitsome
$ pip3 install gitsome

如果要激活gitsomevirtualenv稍后再次运行:

$ workon gitsome

要停用gitsomevirtualenv,运行:

$ deactivate

作为Docker容器运行

您可以在Docker容器中运行gitome,以避免安装Python和pip3当地的。要安装Docker,请查看official Docker documentation

一旦安装了docker,您就可以运行gitome:

$ docker run -ti --rm mariolet/gitsome

您可以使用Docker卷让gitome访问您的工作目录、本地的.gitSomeconfig和.gitconfig:

$ docker run -ti --rm -v $(pwd):/src/              \
   -v ${HOME}/.gitsomeconfig:/root/.gitsomeconfig  \
   -v ${HOME}/.gitconfig:/root/.gitconfig          \
   mariolet/gitsome

如果您经常运行此命令,则可能需要定义别名:

$ alias gitsome="docker run -ti --rm -v $(pwd):/src/              \
                  -v ${HOME}/.gitsomeconfig:/root/.gitsomeconfig  \
                  -v ${HOME}/.gitconfig:/root/.gitconfig          \
                  mariolet/gitsome"

要从源构建Docker映像,请执行以下操作:

$ git clone https://github.com/donnemartin/gitsome.git
$ cd gitsome
$ docker build -t gitsome .

启动gitsome

安装后,运行可选的gitsome带有交互式帮助的自动完成程序:

$ gitsome

运行可选的gitsomeShell将为您提供自动完成、交互式帮助、鱼式建议、Python REPL等

正在运行gh命令

运行GitHub集成命令:

$ gh <command> [param] [options]

注意:运行gitsome不需要执行外壳程序gh命令。之后installinggitsome你可以跑gh来自任何shell的命令

运行gh configure命令

要与GitHub正确集成,gitsome必须正确配置:

$ gh configure

针对GitHub企业用户

使用-e/--enterprise标志:

$ gh configure -e

要查看更多详细信息,请访问gh configure部分

启用Bash完成

默认情况下,gitsome查看以下内容locations to enable bash completions

要添加其他bash完成,请更新~/.xonshrc包含bash完成位置的文件

如果~/.xonshrc不存在,请创建它:

$ touch ~/.xonshrc

例如,如果在/usr/local/etc/my_bash_completion.d/completion.bash,将以下行添加到~/.xonshrc

$BASH_COMPLETIONS.append('/usr/local/etc/my_bash_completion.d/completion.bash')

您将需要重新启动gitsome要使更改生效,请执行以下操作

正在启用gh在外部完成制表符gitsome

你可以跑gh外部的命令gitsome外壳完成器。要启用gh此工作流的制表符完成,请将gh_complete.sh本地文件

让bash知道可以完成gh当前会话中的命令:

$ source /path/to/gh_complete.sh

要为所有终端会话启用制表符完成,请将以下内容添加到您的bashrc文件:

source /path/to/gh_complete.sh

重新加载您的bashrc

$ source ~/.bashrc

提示:.是的缩写source,因此您可以改为运行以下命令:

$ . ~/.bashrc

对于Zsh用户

zsh包括与bash完成兼容的模块

下载gh_complete.sh文件,并将以下内容附加到您的.zshrc

autoload bashcompinit
bashcompinit
source /path/to/gh_complete.sh

重新加载您的zshrc

 $ source ~/.zshrc

可选:安装PILPillow

将化身显示为gh megh user命令需要安装可选的PILPillow依赖性

Windows*和Mac:

$ pip3 install Pillow

*请参阅Windows Support有关化身限制的部分

Ubuntu用户,看看这些instructions on askubuntu

支持的Python版本

  • Python 3.4
  • Python 3.5
  • Python 3.6
  • Python 3.7

gitsome由以下人员提供动力xonsh,它当前不支持Python2.x,如本文中所讨论的ticket

支持的平台

  • Mac OS X
    • 在OS X 10.10上测试
  • Linux、Unix
    • 在Ubuntu 14.04 LTS上测试
  • 窗口
    • 在Windows 10上测试

Windows支持

gitsome已在Windows 10上进行了测试,cmdcmder

虽然您可以使用标准的Windows命令提示符,但使用这两种命令提示符都可能会有更好的体验cmderconemu

纯文本化身

命令gh usergh me将永远拥有-t/--text_avatar标志已启用,因为img2txt不支持Windows上的ANSI头像

配置文件

在Windows上,.gitsomeconfig 文件可在以下位置找到%userprofile%例如:

C:\Users\dmartin\.gitsomeconfig

开发人员安装

如果您有兴趣为gitsome,请运行以下命令:

$ git clone https://github.com/donnemartin/gitsome.git
$ cd gitsome
$ pip3 install -e .
$ pip3 install -r requirements-dev.txt
$ gitsome
$ gh <command> [param] [options]

pip3

如果您在安装时收到一个错误,提示您需要Python 3.4+,这可能是因为您的pip命令是为旧版本的Python配置的。要解决此问题,建议安装pip3

$ sudo apt-get install python3-pip

看这个ticket有关更多详细信息,请参阅

持续集成

有关持续集成的详细信息,请访问Travis CI

单元测试和代码覆盖率

在活动的Python环境中运行单元测试:

$ python tests/run_tests.py

使用运行单元测试tox在多个Python环境中:

$ tox

文档

源代码文档将很快在Readthedocs.org请查看source docstrings

运行以下命令构建文档:

$ scripts/update_docs.sh

贡献

欢迎投稿!

回顾Contributing Guidelines有关如何执行以下操作的详细信息,请执行以下操作:

  • 提交问题
  • 提交拉式请求

学分

联系信息

请随时与我联系,讨论任何问题、问题或评论

我的联系信息可以在我的GitHub page

许可证

我在开放源码许可下向您提供此存储库中的代码和资源。因为这是我的个人存储库,您获得的我的代码和资源的许可证来自我,而不是我的雇主(Facebook)

Copyright 2016 Donne Martin

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.